import { useState } from "react";
import { EyeOff, Eye } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast, Flip } from "react-toastify";
import checkPasswordStrength from "@/lib/strongPassCheck";
import { z } from "zod";
import { useRouter } from "next/navigation";

const passwordResetSchema = z.object({
  newPassword1: z
    .string()
    .min(8, { message: "Password must be at least 8 characters long" }),
  
    newPassword2: z
    .string()
    .min(8, { message: "Password must be at least 8 characters long" }),
});

const PasswordResetForm = ({ onPasswordReset }: {

  onPasswordReset: ( newPassword1: string, newPassword2: string ) => Promise<{
    user: { id: string; email: string };
    message: string;
    status: number;
  }>;
}) => {
  const [password1Visible, setPassword1Visible] = useState(false);
  const [password2Visible, setPassword2Visible] = useState(false)

  const router = useRouter();

  const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(passwordResetSchema)})

  const onSubmit = async (data: any) => {
    try {

      if (data.newPassword1 != data.newPassword2) {
        toast.error("Passwords do not match!", {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });

        return;
      }

      const passwordStrength = checkPasswordStrength(data.newPassword1);
      let passwordStrengthMessage = "";
      if (passwordStrength === 1) {
        passwordStrengthMessage = "Weak password";
      } else if (passwordStrength === 2) {
        passwordStrengthMessage = "Medium password";
      } else {
        passwordStrengthMessage = "Strong password";
      }

      const response = await onPasswordReset(data.newPassword1, data.newPassword2);
      
      console.log(response)

      if (response.status === 200) {

        toast.success("Password reset successful!", {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
        //! ----- redirecting code here-------------//
        router.push("/login");
        toast.info(passwordStrengthMessage, {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      }
    } catch (error: any) {
      // Handle password reset error
      toast.error(error.message, {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  };

  return (
    <Card className="my-12 mx-auto w-full max-w-md p-4">
      <CardHeader>
        <CardTitle className="text-heading4-bold mx-auto mb-8">
          Reset Password
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="grid gap-4">
             <div className="grid gap-2">
              <div className="flex items-center text-black">
                <Label htmlFor="newPassword1">Enter New Password</Label>
              </div>
              <div className="relative select-none">
                <Input
                  id="newPassword1"
                  type={password1Visible ? "text" : "password"}
                  {...register("newPassword1")}
                  className="pr-8"
                />
                {password1Visible ? (
                  <Eye
                    className="absolute top-1/2 right-5 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                    onClick={() => setPassword1Visible(!password1Visible)}
                  />
                ) : (
                  <EyeOff
                    className="absolute top-1/2 right-6 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                    onClick={() => setPassword1Visible(!password1Visible)}
                  />
                )}
              </div>
              {errors.newPassword1 &&
                typeof errors.newPassword1.message === "string" && (
                  <div className="text-red-500">
                    {errors.newPassword1.message}
                  </div>
                )}
            </div>
            <div className="grid gap-2">
              <div className="flex items-center text-black">
                <Label htmlFor="newPassword2">Confirm the Password</Label>
              </div>
              <div className="relative select-none">
                <Input
                  id="newPassword2"
                  type={password2Visible ? "text" : "password"}
                  {...register("newPassword2")}
                  className="pr-8"
                />
                {password2Visible ? (
                  <Eye
                    className="absolute top-1/2 right-5 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                    onClick={() => setPassword2Visible(!password2Visible)}
                  />
                ) : (
                  <EyeOff
                    className="absolute top-1/2 right-6 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                    onClick={() => setPassword2Visible(!password2Visible)}
                  />
                )}
              </div>
              {errors.newPassword2 &&
                typeof errors.newPassword2.message === "string" && (
                  <div className="text-red-500">
                    {errors.newPassword2.message}
                  </div>
                )}
            </div>
            <Button type="submit" className="w-full bg-black text-white">
              Reset Password
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
};

export default PasswordResetForm;
