import { Container, FormTextField } from "@/components";
import { UeckoLogo } from "@/components/UeckoLogo/UeckoLogo";
import { useLogin } from "@/lib/hooks";
import {
  Alert,
  AlertDescription,
  AlertTitle,
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Form,
} from "@/ui";
import { joiResolver } from "@hookform/resolvers/joi";
import Joi from "joi";
import { AlertCircleIcon } from "lucide-react";
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { Link } from "react-router-dom";
import SpanishJoiMessages from "../spanish-joi-messages.json";

type LoginDataForm = {
  email: string;
  password: string;
};

export const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const { mutate: login } = useLogin({
    onSuccess: (data) => {
      const { success, error } = data;
      if (!success && error) {
        form.setError("root", error);
      }
    },
  });

  const form = useForm<LoginDataForm>({
    mode: "onBlur",
    defaultValues: {
      email: "",
      password: "",
    },
    resolver: joiResolver(
      Joi.object({
        email: Joi.string()
          .email({ tlds: { allow: false } })
          .required(),
        password: Joi.string().min(4).alphanum().required(),
      }),
      {
        messages: SpanishJoiMessages,
      }
    ),
  });

  const onSubmit: SubmitHandler<LoginDataForm> = async (data) => {
    console.log(data);
    try {
      setLoading(true);
      login({ email: data.email, password: data.password });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container
      variant={"full"}
      className='p-0 lg:grid lg:min-h-[600px] lg:grid-cols-2 xl:min-h-[800px] h-screen'
    >
      <div className='flex items-center justify-center py-12'>
        <div className='mx-auto grid w-[450px] gap-6'>
          <Card>
            <CardHeader>
              <UeckoLogo className='inline-block m-auto mb-6 align-middle max-w-32' />
              <CardTitle>Presupuestador para distribuidores</CardTitle>
              <CardDescription>Enter your email below to login to your account</CardDescription>
            </CardHeader>
            <CardContent>
              <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)}>
                  <div className='grid items-start gap-6'>
                    <div className='grid gap-6'>
                      <FormTextField
                        disabled={loading}
                        label='Email'
                        type='email'
                        placeholder='micorreo@ejemplo.com'
                        {...form.register("email", {
                          required: true,
                        })}
                        errors={form.formState.errors}
                      />
                    </div>
                    <div className='grid gap-6'>
                      <FormTextField
                        disabled={loading}
                        label='Contraseña'
                        type='password'
                        {...form.register("password", {
                          required: true,
                        })}
                        errors={form.formState.errors}
                      />
                      <div className='mb-4 -mt-2 text-sm'>
                        ¿Has olvidado tu contraseña?
                        <br />
                        <Link to='https://uecko.com/distribuidores' className='underline'>
                          Contacta con nosotros
                        </Link>
                      </div>
                    </div>

                    {form.formState.errors.root?.message && (
                      <Alert variant='destructive'>
                        <AlertCircleIcon className='w-4 h-4' />
                        <AlertTitle>Heads up!</AlertTitle>
                        <AlertDescription>{form.formState.errors.root?.message}</AlertDescription>
                      </Alert>
                    )}

                    <Button disabled={loading} type='submit' className='w-full'>
                      Entrar
                    </Button>

                    <div className='mt-4 text-sm text-center'>
                      ¿Quieres ser distribuidor de Uecko?
                      <br />
                      <Link to='https://uecko.com/distribuidores' className='underline'>
                        Contacta con nosotros
                      </Link>
                    </div>
                  </div>
                </form>
              </Form>
            </CardContent>
          </Card>
        </div>
      </div>

      <div className='hidden bg-muted lg:block'>
        <img
          src='https://uecko.com/assets/img/021/nara2.jpg'
          alt='Image'
          width='1920'
          height='1080'
          className='h-full w-full object-cover dark:brightness-[0.2] dark:grayscale'
        />
      </div>
    </Container>
  );
};
