"use client";

import { useState, useEffect, Suspense } from "react";
import { Button } from "@/components/ui/button";

import { useRouter, useSearchParams } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Eye, EyeOff, Mail, Loader2 } from "lucide-react";
import VerifyOTP from "@/components/verify-otp";
// import {
//   useForgotPasswordMutation,
//   useResetPasswordMutation,
//   useVerifyOtpMutation,
//   useVerify2FAForPasswordResetMutation,
// } from "@/redux/services/auth.api";
import { toast } from "sonner";
import {
  useForgotPassword,
  useResetPassword,
  useVerifyOTP,
} from "@/hooks/use-auth";
import {
  ForgotPasswordResponse,
  ResetPasswordResponse,
  VerifyOTPResponseForPasswordReset,
} from "@/types/api";

// Component that uses useSearchParams
function ForgotPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const getToken = searchParams.get("token");

  const [step, setStep] = useState<number>(0);
  const [token, setToken] = useState("");
  const [twoFactorCode, setTwoFactorCode] = useState("");

  useEffect(() => {
    if (getToken) {
      setStep(2);
      setToken(getToken);
    }
  }, [getToken]);

  const [email, setEmail] = useState("");
  const [userId, setUserId] = useState("");
  const [password, setPassword] = useState("");
  const [continueLoader, setContinueLoader] = useState(false);
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [error, setError] = useState("");
  const [value, setValue] = useState("");
  // API
  const { mutateAsync: forgotPasswordApi } = useForgotPassword();
  const { mutateAsync: verifyOTP } = useVerifyOTP();
  const { mutateAsync: resetPasswordApi } = useResetPassword();
  // const [verifyOtpApi] = useVerifyOtpMutation({});
  // const [resetPasswordApi] = useResetPasswordMutation({});
  // const [verify2FAForPasswordResetApi] = useVerify2FAForPasswordResetMutation(
  //   {}
  // );

  const handleValueChange = (valueFromChild: string) => {
    setValue(valueFromChild);
  };

  const handleVerifyOTP = () => {
    // console.log("Verifying:", value);
    verifyOTP({ userId, otp: value }).then(
      (res: VerifyOTPResponseForPasswordReset) => {
        console.log(res);
        if (res?.success) {
          setStep(2);
          setToken(res.data!.token!);
        } else {
          toast.error(res.message);
        }
      }
    );
    // verifyOtpApi({ userId, otp: value })
    //   .unwrap()
    //   .then((res) => {
    //     // console.log("res", res);
    //     if (res.success) {
    //       toast.success(res.message);
    //       setToken(res.data.token!);
    //       setStep(2);
    //     } else {
    //       toast.error(res.message);
    //     }
    //     // setStep(1); // maybe move this here after success
    //   })
    //   .catch((err) => {
    //     console.log("API Error:", err);
    //   });
  };

  const verify2FAForPasswordReset = () => {
    if (!twoFactorCode || twoFactorCode.length !== 6) {
      toast.error("Please enter a valid 6-digit OTP code");
      return;
    }

    verifyOTP({ userId, otp: twoFactorCode }).then(
      (res: VerifyOTPResponseForPasswordReset) => {
        console.log(res);
        if (res?.success) {
          setStep(2);
          setToken(res.data!.token!);
        } else {
          toast.error(res.message);
        }
      }
    );

    // verify2FAForPasswordResetApi({
    //   admin_id: adminId,
    //   two_factor_code: twoFactorCode,
    //   is_forgot_password: true,
    // })
    //   .unwrap()
    //   .then((res) => {
    //     console.log("MFA verification response:", res);
    //     if (res.status === 200) {
    //       toast.success("MFA verification successful");
    //       setToken(res.data.reset_token);
    //       setStep(2); // Move to password reset step
    //     } else {
    //       toast.error(res.message || "MFA verification failed");
    //     }
    //   })
    //   .catch((err) => {
    //     console.log("MFA API Error:", err);
    //     toast.error("MFA verification failed. Please try again.");
    //   });
  };

  const findAccount = () => {
    setContinueLoader(true);
    // console.log("email", email);

    if (!email) {
      // console.log("Email is required before submitting!");
      setContinueLoader(false);
      return;
    }

    forgotPasswordApi(email).then((res: ForgotPasswordResponse) => {
      console.log(res);
      if (res?.success) {
        setStep(1);
        setUserId(res.data!.user!._id!);
      } else {
        toast.error(res.message);
      }
    });
    setContinueLoader(false);
    // forgotPasswordApi({ email })
    //   .unwrap()
    //   .then((res) => {
    //     console.log("res", res);
    //     if (res.success) {
    //       toast.success(res.message);
    //       setUserId(res.data!.user!._id!);
    //       setStep(1);
    //     } else if (res.data?.is_two_factor) {
    //       // Handle 2FA-enabled account
    //       setAdminId(res.data.admin_id!);
    //       setStep(3); // New step for 2FA verification
    //       toast.info(
    //         "MFA is enabled for this account. Please enter your MFA code."
    //       );
    //     } else {
    //       toast.error(res.message);
    //     }
    //     // setStep(1); // maybe move this here after success
    //   })
    //   .catch((err) => {
    //     console.log("API Error:", err);
    //   })
    //   .finally(() => {
    //     setContinueLoader(false);
    //   });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    // console.log("reset");
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    if (password.length < 8) {
      setError("Password must be at least 8 characters long");
      return;
    }

    try {
      // Here you would typically make an API call to update the password
      // await updatePassword(password)
      // console.log("password");
      // console.log(password);
      resetPasswordApi({ password, token }).then(
        (res: ResetPasswordResponse) => {
          console.log(res);
          if (res?.success) {
            toast.success(res.message);
            router.push("/login");
          } else {
            toast.error(res.message);
          }
        }
      );
      // resetPasswordApi({ token, password })
      //   .unwrap()
      //   .then((res) => {
      //     console.log("res", res);
      //     if (res.status === 200) {
      //       toast.success(res.message);
      //       router.push("/login");
      //     } else {
      //       toast.error(res.message);
      //     }
      //     // setStep(1); // maybe move this here after success
      //   })
      //   .catch((err) => {
      //     console.log("API Error:", err);
      //     if (err.data.message === "Invalid or expired reset token") {
      //       toast.error("Invalid or expired reset token");
      //       setStep(3);
      //     }
      //   });
      // toast({
      //   title: "Success",
      //   description: "Your password has been updated successfully.",
      // });
    } catch (err) {
      console.log(err);
      setError("Failed to update password. Please try again.");
    }
  };

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  const toggleConfirmPasswordVisibility = () => {
    setShowConfirmPassword(!showConfirmPassword);
  };
  return (
    <div className="relative flex flex-col items-center justify-center p-8">
      {step === 0 && (
        <>
          <div className="flex flex-col items-center justify-center p-8 ">
            <div className="text-center mb-8">
              <h1 className="text-2xl font-bold mb-2 text-white ">
                Find Your Account
              </h1>
              <h2 className="text-white">
                Please enter your email to rest your password
              </h2>
            </div>

            {/* OTP Input Fields */}
            <div className="space-y-2 w-[30vw]">
              <Label htmlFor="email" className="text-white">
                Email
              </Label>
              <div className="relative">
                <Input
                  id="email"
                  type="email"
                  placeholder="Enter your Email Address"
                  className={cn("pr-10 bg-white")}
                  onChange={(e) => setEmail(e.target.value)}
                  value={email}
                />
                <Badge
                  variant={"outline"}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-primary"
                >
                  <Mail />
                </Badge>
              </div>
            </div>

            {/* Verify Button */}
            <Button
              className="w-[30vw] mt-10  py-2 rounded-md mb-8 flex items-center justify-center"
              onClick={findAccount}
              disabled={continueLoader}
            >
              {continueLoader ? (
                <>
                  <Loader2 className="animate-spin mr-2 h-4 w-4" />
                  Loading...
                </>
              ) : (
                "Continue"
              )}
            </Button>
          </div>
        </>
      )}

      {step === 1 && (
        <VerifyOTP
          valueChanger={handleValueChange}
          value={value}
          verifyOTP={handleVerifyOTP}
          email={email}
          userId={userId}
        />
      )}

      {step === 2 && (
        <>
          <div className="text-center mb-8">
            <h1 className="text-2xl font-bold mb-2">Reset Password</h1>
            <p className="text-muted-foreground">
              Please enter your details to Reset Password
            </p>
          </div>

          <form onSubmit={handleSubmit} className="w-full max-w-md space-y-6">
            <div className="space-y-2">
              <Label htmlFor="new-password">New Password</Label>
              <div className="relative">
                <Input
                  id="new-password"
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pr-10 bg-white"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                  onClick={togglePasswordVisibility}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4 text-primary-gradient" />
                  ) : (
                    <Eye className="h-4 w-4 text-primary-gradient" />
                  )}
                </Button>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirm-password">Confirm Password</Label>
              <div className="relative">
                <Input
                  id="confirm-password"
                  type={showConfirmPassword ? "text" : "password"}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="pr-10 bg-white"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                  onClick={toggleConfirmPasswordVisibility}
                >
                  {showConfirmPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            {error && <p className="text-sm text-primary-gradient">{error}</p>}

            <Button type="submit" className="w-full hover:opacity-90">
              Save
            </Button>
          </form>
        </>
      )}

      {step === 3 && (
        <>
          <div className="text-center mb-8">
            <h1 className="text-2xl font-bold mb-2">OTP Authentication</h1>
            <p className="text-muted-foreground">
              Please enter your OTP code from your Email
            </p>
          </div>

          <div className="w-full max-w-md space-y-6">
            <div className="space-y-2">
              <Label htmlFor="2fa-code">OTP Code</Label>
              <Input
                id="2fa-code"
                type="text"
                placeholder="Enter 6-digit code"
                value={twoFactorCode}
                onChange={(e) => setTwoFactorCode(e.target.value)}
                maxLength={6}
                className="text-center text-lg tracking-widest bg-white"
              />
            </div>

            <Button onClick={verify2FAForPasswordReset} className="w-full">
              Verify OTP
            </Button>
          </div>
        </>
      )}
    </div>
  );
}

// Main component with Suspense boundary
export default function VerificationForm() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ForgotPasswordForm />
    </Suspense>
  );
}
