import { Button } from "~/components/ui/button";
import AuthLayout from "../layout/Auth";
import { useForm, SubmitHandler, FormProvider } from "react-hook-form";
import Heading from "~/components/core/Text/Heading";
import FormElement from "~/components/core/FormElements/FormElement";
import { Link, useNavigate } from "@remix-run/react";
import SocialAuth from "~/components/reusable/SocialAuth";
import { LoginProps } from "~/store/features/auth/type";
import { useLoginMutation } from "~/store/features/auth/login";
import { useToast } from "~/hooks/use-toast";
import { CircleCheck, TriangleAlert } from "lucide-react";

const AuthHeading = {
  title: "Ready to pick up where you left off?",
  subtitle:
    "Log in to unleash your creativity, access your designs, orders, and keep personalizing your products",
};

const MainHeading = {
  title: "Login",
  subtitle: "Hey there! Welcome back 👋",
};

const Login = () => {
  const navigate = useNavigate();
  const methods = useForm<LoginProps>();

  const { handleSubmit } = methods;

  const { toast } = useToast();

  const [login, { isLoading }] = useLoginMutation();

  const onSubmit: SubmitHandler<LoginProps> = (data) => {
    login(data)
      .unwrap()
      .then((res) => {
        console.log(res);
        toast({
          title: "Success",
          description: "You have successfully logged in",
          variant: "success",
          icon: (
            <CircleCheck
              color="green"
              size={35}
              className="bg-green-100 p-1 rounded"
            />
          ),
        });
        if (window.history.state && window.history.state.idx > 0) {
          navigate(-1);
        } else {
          navigate("/");
        }
      })
      .catch((err) => {
        if (err?.data?.data) {
          toast({
            title: "An error occurred",
            description: err?.data?.data?.non_field_errors[0]
              ? err?.data?.data?.non_field_errors[0]
              : "Something went wrong, please try again",
            variant: "destructive",
            icon: (
              <TriangleAlert
                color="red"
                size={35}
                className="bg-red-100 p-1 rounded"
              />
            ),
          });
        } else {
          toast({
            title: "An error occurred",
            description: "Something went wrong, please try again",
            variant: "destructive",
            icon: (
              <TriangleAlert
                color="red"
                size={35}
                className="bg-red-100 p-1 rounded"
              />
            ),
          });
        }
        // console.log(err?.data?.data?.non_field_errors[0]);
      });
  };

  return (
    <AuthLayout title={AuthHeading.title} subtitle={AuthHeading.subtitle}>
      <FormProvider {...methods}>
        <form
          className="flex flex-col gap-5 w-full"
          onSubmit={handleSubmit(onSubmit)}
        >
          <Heading title={MainHeading.title} subtitle={MainHeading.subtitle} />
          <FormElement type="email" fieldName="email" required />
          <FormElement type="password" fieldName="password" required />
          <Link
            to="/forgot-password"
            className="font-semibold self-end hover:text-primary"
          >
            Forgot your password?
          </Link>
          <Button size="lg" text="Log in" isLoading={isLoading} />
          <SocialAuth displayText="or login with" />
          <p className="flex gap-2 justify-center font-semibold mb-10">
            Don&apos;t have an account?{" "}
            <Link to="/user/signup" className="text-primary">
              Create account
            </Link>
          </p>
        </form>
      </FormProvider>
    </AuthLayout>
  );
};

export default Login;
