import { useForm, SubmitHandler, FormProvider } from "react-hook-form";
import { useEffect, useState } from "react";
import AuthLayout from "../layout/Auth";
import Heading from "~/components/core/Text/Heading";
import FormElement from "~/components/core/FormElements/FormElement";
import PasswordCriteria from "~/components/reusable/PasswordCriteria";
import { Link, useNavigate, useParams } from "@remix-run/react";
import { ResetPasswordProps } from "~/store/features/auth/type";
import { Button } from "~/components/ui/button";
import { useResetPasswordMutation } from "~/store/features/auth/signup";
import { CircleCheck, TriangleAlert } from "lucide-react";
import { useToast } from "~/hooks/use-toast";
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 [passwordCriteria, setPasswordCriteria] = useState({
    specialCharacter: false,
    containsUppercase: false,
    containsLowercase: false,
    containsNumber: false,
    eightCharacter: false,
  });
  const [isOpen, setIsOpen] = useState(false);

  const navigate = useNavigate();
  const { toast } = useToast();
  const { uid, token } = useParams();
  const methods = useForm<ResetPasswordProps>();

  const { handleSubmit, watch } = methods;
  const password = watch("new_password1");

  const [resetPassword, { isLoading }] = useResetPasswordMutation();

  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 onSubmit: SubmitHandler<ResetPasswordProps> = (data) => {
    resetPassword({
      ...data,
      uid: uid,
      token: token,
    })
      .unwrap()
      .then((res) => {
        console.log(res);

        if (res?.success) {
          setIsOpen(true);
        }
      })
      .catch((err) => {
        if (err?.data?.data?.non_field_errors) {
          toast({
            title: "An error occurred",
            description: err?.data?.data?.token[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?.uid[0]
              ? err?.data?.data?.uid[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]);
      });

    console.log(data);
  };

  return (
    <AuthLayout title="" subtitle="">
      <FormProvider {...methods}>
        <form
          className="flex flex-col gap-5 w-full"
          onSubmit={handleSubmit(onSubmit)}
        >
          <Heading
            title="Change Password"
            subtitle="Enter new password and confirm password to reset your forgotten password"
          />
          <FormElement
            validateFn={validatePassword}
            type="password"
            fieldName="new_password1"
            fieldLabel="New Password"
            isValidated
            required
          />
          <PasswordCriteria criteria={passwordCriteria} />
          <FormElement
            validateFn={validatePassword}
            type="password"
            fieldName="new_password2"
            fieldLabel="Confrim Password"
            isValidated
            required
          />
          <Button size="lg" text="Reset Password" isLoading={isLoading} />

          <Link to="/user/login" className="text-primary mx-auto">
            Back To Login
          </Link>
        </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">
              Password has successfully reset
            </h2>
            <p className="text-sm text-muted-foreground">
              Your password has been successfully reset. You can now login with
              your new password.
            </p>
          </div>
          <hr />
          <Button
            variant="default"
            className="w-full"
            onClick={() => {
              navigate("/user/login");
            }}
            text="Proceed to login"
          />
        </div>
      </Dialog>
    </AuthLayout>
  );
};

export default Signup;
