"use client";

import {
  useForgotPasswordMutation,
  useResetPasswordMutation,
} from "@/api/auth.api";
import { parseApiError } from "@/api/utils/error-handler";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-hot-toast";
import OtpInput from "@/components/common/OtpInput";

type Step = "EMAIL" | "VERIFICATION";

interface IForgotPasswordForm {
  email: string;
}

interface IResetPasswordForm {
  code: string;
  password: string;
  confirmPassword: string;
}

const MailIcon = () => (
  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
  </svg>
);

const LockIcon = () => (
  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
    <rect x="3" y="11" width="18" height="11" rx="2" />
    <path d="M7 11V7a5 5 0 0110 0v4" />
  </svg>
);

const EyeOffIcon = () => (
  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
  </svg>
);

const EyeIcon = () => (
  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
  </svg>
);

const inputClass = (hasError?: boolean) =>
  `w-full py-2.5 pl-10 pr-10 text-sm border rounded-xl bg-white text-[#111827] placeholder:text-[#d1d5db] outline-none transition-all focus:border-transparent focus:ring-2 focus:ring-[#60a5fa] ${
    hasError ? "border-red-400" : "border-[#e5e7eb]"
  }`;

export default function ForgotPasswordPage() {
  const [currentStep, setCurrentStep] = useState<Step>("EMAIL");
  const [resetToken, setResetToken] = useState("");
  const [resetEmail, setResetEmail] = useState("");
  const [countdown, setCountdown] = useState(0);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const router = useRouter();

  const [message, setMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  const [forgotPassword, { isLoading: isForgotLoading }] =
    useForgotPasswordMutation();
  const [resetPassword, { isLoading: isResetLoading }] =
    useResetPasswordMutation();

  const {
    register: registerForgot,
    handleSubmit: handleSubmitForgot,
    getValues: getForgotValues,
    formState: { errors: forgotErrors },
  } = useForm<IForgotPasswordForm>();

  const {
    register: registerReset,
    handleSubmit: handleSubmitReset,
    setValue: setResetValue,
    setError: setResetError,
    clearErrors: clearResetErrors,
    watch: watchReset,
    formState: { errors: resetErrors },
  } = useForm<IResetPasswordForm>({
    defaultValues: {
      code: "",
      password: "",
      confirmPassword: "",
    },
  });

  const password = watchReset("password");
  const code = watchReset("code");

  const onForgotSubmit = async (data: IForgotPasswordForm) => {
    setMessage(null);
    try {
      const response = await forgotPassword({ email: data.email }).unwrap();

      const token =
        response?.responseData?.resetPasswordToken ||
        response?.data?.resetPasswordToken ||
        (response as any)?.resetPasswordToken;

      if (token) {
        setResetToken(token);
        setResetEmail(data.email);
        setCurrentStep("VERIFICATION");
        setResetValue("code", "");
        setCountdown(30);
        setMessage({
          type: "success",
          text: "Verification code sent to your email.",
        });
      } else {
        setMessage({
          type: "error",
          text: "Reset token not found in server response.",
        });
      }
    } catch (error: any) {
      setMessage({
        type: "error",
        text: parseApiError(error),
      });
    }
  };

  const onResetSubmit = async (data: IResetPasswordForm) => {
    setMessage(null);
    // The OTP field is controlled via setValue, so guard it explicitly.
    if (!code?.trim()) {
      setResetError("code", {
        type: "required",
        message: "Verification code is required.",
      });
      return;
    }
    try {
      await resetPassword({
        resetPasswordToken: resetToken,
        verificationCode: data.code,
        password: data.password,
      }).unwrap();

      setMessage({
        type: "success",
        text: "Password reset successfully! Redirecting to login...",
      });
      setTimeout(() => {
        router.push("/login");
      }, 2000);
    } catch (error: any) {
      setMessage({
        type: "error",
        text: parseApiError(error),
      });
    }
  };

  const handleResendOtp = async () => {
    setMessage(null);
    try {
      const email = getForgotValues("email");
      const response = await forgotPassword({ email }).unwrap();

      const token =
        response?.responseData?.resetPasswordToken ||
        response?.data?.resetPasswordToken ||
        (response as any)?.resetPasswordToken;

      if (token) {
        setResetToken(token);
        setResetValue("code", "");
        setCountdown(30);
        toast.success("OTP resent successfully!");
      } else {
        toast.error("Reset token not found in server response.");
      }
    } catch (error: any) {
      toast.error(parseApiError(error));
    }
  };

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (currentStep === "VERIFICATION" && countdown > 0) {
      timer = setTimeout(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
    }
    return () => clearTimeout(timer);
  }, [currentStep, countdown]);

  return (
    <div className="w-full">
      <div className="text-center mb-8">
        <h1 className="text-2xl font-bold text-[#111827]">
          {currentStep === "EMAIL" ? "Forgot password" : "Reset password"}
        </h1>
        <p className="mt-1.5 text-sm text-[#6b7280]">
          {currentStep === "EMAIL" ? (
            "Enter your email and we'll send you a reset code"
          ) : (
            <>
              Enter the 4-digit code sent to{" "}
              <span className="font-semibold text-[#374151]">{resetEmail}</span>
            </>
          )}
        </p>
      </div>

      <div className="bg-white rounded-2xl shadow-[0_25px_50px_-12px_rgba(0,0,0,0.25)] p-8">
        {message && (
          <div
            className={`mb-5 p-3 rounded-xl text-sm font-medium border whitespace-pre-line ${
              message.type === "success"
                ? "bg-green-50 border-green-200 text-green-700"
                : "bg-red-50 border-red-200 text-red-700"
            }`}
          >
            {message.text}
          </div>
        )}

        {currentStep === "EMAIL" ? (
          <form
            onSubmit={handleSubmitForgot(onForgotSubmit)}
            className="flex flex-col gap-5"
          >
            <div>
              <label className="block text-sm font-semibold text-[#374151] mb-1.5">
                Email address
              </label>
              <div className="relative">
                <span className="absolute left-3.5 top-1/2 -translate-y-1/2 flex items-center pointer-events-none text-[#9ca3af]">
                  <MailIcon />
                </span>
                <input
                  type="email"
                  placeholder="you@example.com"
                  autoComplete="email"
                  {...registerForgot("email", {
                    required: "Email is required",
                    pattern: {
                      value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                      message: "Invalid email format",
                    },
                  })}
                  className={inputClass(!!forgotErrors.email)}
                />
              </div>
              {forgotErrors.email && (
                <p className="mt-1 text-xs text-[#ef4444]">
                  {forgotErrors.email.message}
                </p>
              )}
            </div>

            <button
              type="submit"
              disabled={isForgotLoading}
              className="w-full py-3 rounded-xl text-sm font-semibold text-white bg-[#3b82f6] hover:bg-[#2563eb] border-none cursor-pointer transition-colors disabled:opacity-50"
            >
              {isForgotLoading ? "Sending..." : "Send reset code"}
            </button>
          </form>
        ) : (
          <form
            onSubmit={handleSubmitReset(onResetSubmit)}
            className="flex flex-col gap-5"
          >
            <div>
              <label className="block text-sm font-semibold text-[#374151] mb-1.5">
                Verification code
              </label>
              <OtpInput
                value={code}
                onChange={(val) => {
                  setResetValue("code", val);
                  if (val) clearResetErrors("code");
                }}
                error={resetErrors.code}
              />
              <p className="mt-2 text-xs text-[#6b7280]">
                Didn't receive a code?{" "}
                <button
                  type="button"
                  disabled={isForgotLoading || countdown > 0}
                  onClick={handleResendOtp}
                  className={`font-semibold text-[#3b82f6] hover:text-[#2563eb] bg-transparent border-none p-0 disabled:opacity-50 ${
                    isForgotLoading || countdown > 0
                      ? "cursor-not-allowed"
                      : "cursor-pointer"
                  }`}
                >
                  {isForgotLoading
                    ? "Sending..."
                    : countdown > 0
                      ? `Resend in ${countdown}s`
                      : "Resend code"}
                </button>
              </p>
            </div>

            <div>
              <label className="block text-sm font-semibold text-[#374151] mb-1.5">
                New password
              </label>
              <div className="relative">
                <span className="absolute left-3.5 top-1/2 -translate-y-1/2 flex items-center pointer-events-none text-[#9ca3af]">
                  <LockIcon />
                </span>
                <input
                  type={showPassword ? "text" : "password"}
                  placeholder="••••••••"
                  autoComplete="new-password"
                  {...registerReset("password", {
                    required: "Password is required",
                    pattern: {
                      value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/,
                      message:
                        "Minimum 8 characters, including 1 number, 1 uppercase & 1 lowercase letter.",
                    },
                  })}
                  className={inputClass(!!resetErrors.password)}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 bg-transparent border-none cursor-pointer text-[#9ca3af] hover:text-[#6b7280] flex items-center p-0.5 transition-colors"
                >
                  {showPassword ? <EyeOffIcon /> : <EyeIcon />}
                </button>
              </div>
              <p
                className={`mt-1 text-xs ${resetErrors.password ? "text-[#ef4444]" : "text-[#6b7280]"}`}
              >
                {resetErrors.password?.message ??
                  "Minimum 8 characters, including 1 number, 1 uppercase & 1 lowercase letter."}
              </p>
            </div>

            <div>
              <label className="block text-sm font-semibold text-[#374151] mb-1.5">
                Confirm password
              </label>
              <div className="relative">
                <span className="absolute left-3.5 top-1/2 -translate-y-1/2 flex items-center pointer-events-none text-[#9ca3af]">
                  <LockIcon />
                </span>
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  placeholder="••••••••"
                  autoComplete="new-password"
                  {...registerReset("confirmPassword", {
                    required: "Please confirm your password",
                    validate: (value) =>
                      value === password || "Passwords do not match",
                  })}
                  className={inputClass(!!resetErrors.confirmPassword)}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 bg-transparent border-none cursor-pointer text-[#9ca3af] hover:text-[#6b7280] flex items-center p-0.5 transition-colors"
                >
                  {showConfirmPassword ? <EyeOffIcon /> : <EyeIcon />}
                </button>
              </div>
              {resetErrors.confirmPassword && (
                <p className="mt-1 text-xs text-[#ef4444]">
                  {resetErrors.confirmPassword.message}
                </p>
              )}
            </div>

            <button
              type="submit"
              disabled={isResetLoading}
              className="w-full py-3 rounded-xl text-sm font-semibold text-white bg-[#3b82f6] hover:bg-[#2563eb] border-none cursor-pointer transition-colors disabled:opacity-50"
            >
              {isResetLoading ? "Resetting..." : "Reset password"}
            </button>

            <button
              type="button"
              onClick={() => setCurrentStep("EMAIL")}
              className="text-sm font-medium text-[#3b82f6] hover:text-[#2563eb] bg-transparent border-none cursor-pointer"
            >
              Back to email
            </button>
          </form>
        )}

        <div className="flex items-center gap-3 my-6">
          <div className="flex-1 h-px bg-[#f3f4f6]" />
          <span className="text-xs text-[#9ca3af] whitespace-nowrap">
            Remember your password?
          </span>
          <div className="flex-1 h-px bg-[#f3f4f6]" />
        </div>

        <Link
          href="/login"
          className="block w-full py-2.5 rounded-xl text-sm font-semibold text-[#374151] bg-white border border-[#e5e7eb] text-center no-underline hover:bg-[#f9fafb] transition-colors"
        >
          Back to sign in
        </Link>
      </div>
    </div>
  );
}
