import { useForm, SubmitHandler, FormProvider } from "react-hook-form";
import { useEffect, useState } from "react";
import {
  useResendOtpMutation,
  useSignUpMutation,
} from "~/store/features/auth/signup";
import AuthLayout from "../layout/Auth";
import Heading from "~/components/core/Text/Heading";
import FormElement from "~/components/core/FormElements/FormElement";
import SocialAuth from "~/components/reusable/SocialAuth";
import PasswordCriteria from "~/components/reusable/PasswordCriteria";
import { SignupProps } from "~/store/features/auth/type";
import { Button } from "~/components/ui/button";
import { useToast } from "~/hooks/use-toast";
import { CircleCheck, TriangleAlert } from "lucide-react";
import { useNavigate, Link } from "@remix-run/react";
import { Dialog } from "~/components/ui/dialog";

const checkPasswordCriteria = (password: string) => ({
  specialCharacter: /[#?!@$%^&*-]/.test(password),
  containsUppercase: /[A-Z]/.test(password),
  containsLowercase: /[a-z]/.test(password),
  containsNumber: /[0-9]/.test(password),
  eightCharacter: password.length >= 8,
});

const Signup = () => {
  const { toast } = useToast();
  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [timer, setTimer] = useState(900); // 900 seconds = 15 minutes
  const [isDisabled, setIsDisabled] = useState(true);

  const [passwordCriteria, setPasswordCriteria] = useState({
    specialCharacter: false,
    containsUppercase: false,
    containsLowercase: false,
    containsNumber: false,
    eightCharacter: false,
  });

  const methods = useForm<SignupProps>();
  const { handleSubmit, watch } = methods;
  const password = watch("password");

  useEffect(() => {
    if (timer > 0) {
      const countdown = setInterval(() => {
        setTimer((prev) => prev - 1);
      }, 1000);
      return () => clearInterval(countdown);
    } else {
      setIsDisabled(false);
    }
  }, [timer]);

  const [resendOtp, { isLoading: resendOtpLoading }] = useResendOtpMutation();
  const [signup, { isLoading }] = useSignUpMutation();

  useEffect(() => {
    setPasswordCriteria(checkPasswordCriteria(password || ""));
  }, [password]);

  const validatePassword = (value: string) => {
    const criteria = checkPasswordCriteria(value);

    if (!criteria.eightCharacter) {
      return "Password must be at least 8 characters long.";
    }
    if (!criteria.containsUppercase) {
      return "Password must contain at least one uppercase letter.";
    }
    if (!criteria.containsLowercase) {
      return "Password must contain at least one lowercase letter.";
    }
    if (!criteria.containsNumber) {
      return "Password must contain at least one number.";
    }
    if (!criteria.specialCharacter) {
      return "Password must contain at least one special character.";
    }

    return true;
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = time % 60;
    return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
  };

  const handleResendOtp = () => {
    resendOtp({ email });
    setTimer(900); // Reset timer to 15 minutes
    setIsDisabled(true);
  };

  const onSubmit: SubmitHandler<SignupProps> = (data) => {
    signup(data)
      .unwrap()
      .then((res) => {
        if (res?.success) {
          setEmail(data?.email);
          setIsOpen(true);
          toast({
            title: `Account created successfully`,
            description: res?.data?.detail,
            variant: "success",
            icon: (
              <CircleCheck
                color="green"
                size={35}
                className="bg-green-100 p-1 rounded"
              />
            ),
          });
        }
      })
      .catch((err) => {
        if (err?.data?.data?.non_field_errors) {
          toast({
            title: "An error occurred",
            description: err?.data?.data?.non_field_errors[0],
            variant: "destructive",
            icon: (
              <TriangleAlert
                color="red"
                size={35}
                className="bg-red-100 p-1 rounded"
              />
            ),
          });
        } else if (err?.data?.data) {
          toast({
            title: "An error occurred",
            description: err?.data?.data?.username[0]
              ? err?.data?.data?.username[0]
              : err?.data?.data?.email[0],
            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]);
      });

    // console.log(data);
  };

  return (
    <AuthLayout
      title="Let's make something awesome together"
      subtitle="Sign up to start creating, customizing, and shopping for personalized products. It's super easy!"
    >
      <FormProvider {...methods}>
        <form
          className="flex flex-col gap-5 w-full"
          onSubmit={handleSubmit(onSubmit)}
        >
          <Heading title="Sign Up" subtitle="Let's go! Create an account ✨" />
          <div className="flex gap-5">
            <FormElement type="text" fieldName="first_name" required />
            <FormElement type="text" fieldName="last_name" required />
          </div>
          <div className="flex gap-5">
            <FormElement type="text" fieldName="username" required />
            <FormElement type="phone" fieldName="phone_number" required />
          </div>
          <FormElement type="email" fieldName="email" required />
          <FormElement
            validateFn={validatePassword}
            type="password"
            fieldName="password"
            isValidated
            required
          />
          <PasswordCriteria criteria={passwordCriteria} />
          <Button size="lg" text="Sign Up" isLoading={isLoading} />
          <SocialAuth displayText="or sign up with" />
          <p className="flex gap-2 justify-center mb-10 font-semibold">
            Have an account already?{" "}
            <Link to="/user/login" className="text-primary">
              Log in
            </Link>
          </p>
        </form>
      </FormProvider>

      <Dialog isOpen={isOpen}>
        <div className="space-y-4">
          <CircleCheck
            color="green"
            size={35}
            className="bg-green-100 p-2 rounded-lg absolute top-6"
          />
          <div>
            <h2 className="text-2xl font-semibold">Verification email sent</h2>
            <p className="text-sm text-muted-foreground">
              A verification email has been sent to {email}
            </p>
            <p className="flex gap-2 text-sm text-muted-foreground my-4">
              Didn&apos;t the link?
              <Button
                onClick={handleResendOtp}
                variant="link"
                size="link"
                className="text-sm"
                text={
                  resendOtpLoading
                    ? "Sending, please wait..."
                    : isDisabled
                    ? `Resend in ${formatTime(timer)}`
                    : "Send a new code"
                }
                disabled={isDisabled || isLoading}
              />
            </p>
          </div>
          <hr />
          <Button
            variant="default"
            className="w-full"
            onClick={() => {
              navigate("/user/login");
            }}
            text="Go to login"
          />
        </div>
      </Dialog>
    </AuthLayout>
  );
};

export default Signup;
