/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { toast } from "sonner";
import { ArrowLeft, Clock } from "lucide-react";
import { requestResetAction, verifyResetAction, submitResetAction } from "@/actions/auth.actions";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";

type Step = "REQUEST" | "VERIFY" | "SUBMIT";

const OTP_EXPIRY_SECONDS = 5 * 60; // 5 minutes

function formatTime(seconds: number) {
  const m = Math.floor(seconds / 60).toString().padStart(2, "0");
  const s = (seconds % 60).toString().padStart(2, "0");
  return `${m}:${s}`;
}

export default function SetPasswordForm() {
  const router = useRouter();
  const [step, setStep] = useState<Step>("REQUEST");
  const [identifier, setIdentifier] = useState("");
  const [otp, setOtp] = useState("");
  const [loading, setLoading] = useState(false);
  const [timeLeft, setTimeLeft] = useState(OTP_EXPIRY_SECONDS);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const identifierRef = useRef<HTMLInputElement>(null);
  const otpRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);

  // Start/reset countdown when moving to VERIFY step
  useEffect(() => {
    if (step === "VERIFY") {
      setTimeLeft(OTP_EXPIRY_SECONDS);
      timerRef.current = setInterval(() => {
        setTimeLeft((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current!);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } else {
      if (timerRef.current) clearInterval(timerRef.current);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [step]);

  const handleRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    const idVal = identifierRef.current?.value.trim() || "";
    if (!idVal) {
      toast.error("Please enter your email or mobile number");
      return;
    }

    setLoading(true);
    const toastId = toast.loading("Sending OTP...");
    try {
      const res = await requestResetAction({ identifier: idVal });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success(res.message);
        setIdentifier(idVal);
        setStep("VERIFY");
      } else {
        toast.error(res.message || "Failed to send OTP");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    if (timeLeft === 0) {
      toast.error("OTP has expired. Please request a new one.");
      setStep("REQUEST");
      return;
    }
    const otpVal = otpRef.current?.value.trim() || "";
    if (!otpVal) {
      toast.error("Please enter the OTP code");
      return;
    }

    setLoading(true);
    const toastId = toast.loading("Verifying OTP...");
    try {
      const res = await verifyResetAction({ identifier, otp: otpVal });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success(res.message);
        setOtp(otpVal);
        setStep("SUBMIT");
      } else {
        toast.error(res.message || "Invalid OTP code");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const passwordVal = passwordRef.current?.value || "";
    if (passwordVal.length < 6) {
      toast.error("Password must be at least 6 characters");
      return;
    }

    setLoading(true);
    const toastId = toast.loading("Setting your password...");
    try {
      const res = await submitResetAction({ identifier, otp, password: passwordVal });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success("Password updated successfully!");
        router.push("/login");
      } else {
        toast.error(res.message || "Failed to update password");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-zinc-50 dark:bg-zinc-950 px-4 pt-24 pb-12 lg:pt-32">
      <div className="w-full max-w-md mb-4 flex justify-start">
        <Link
          href="/"
          className="inline-flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-zinc-500 hover:text-brand-accent transition-colors"
        >
          <ArrowLeft className="w-3.5 h-3.5" />
          Back to Home
        </Link>
      </div>
      <div className="w-full max-w-md space-y-8">
        <Card className="border border-zinc-200/80 bg-white/70 shadow-xl backdrop-blur-md dark:border-zinc-800/80 dark:bg-zinc-900/70 rounded-md">
          <CardHeader className="space-y-1 text-center">
            <CardTitle className="text-xl lg:text-2xl font-black text-zinc-900 dark:text-white uppercase tracking-wider">
              {step === "REQUEST" && "Set / Reset Password"}
              {step === "VERIFY" && "Verify OTP"}
              {step === "SUBMIT" && "Create Password"}
            </CardTitle>
            <CardDescription className="text-zinc-500 dark:text-zinc-400 text-xs">
              {step === "REQUEST" && "Enter your email or phone number to receive a verification OTP."}
              {step === "VERIFY" && `We've sent an OTP code to ${identifier}.`}
              {step === "SUBMIT" && "Enter your new secure login password."}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {step === "REQUEST" && (
              <form onSubmit={handleRequest} className="space-y-4">
                <div className="space-y-1">
                  <Label htmlFor="identifier" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Email or Mobile Number</Label>
                  <Input
                    id="identifier"
                    ref={identifierRef}
                    placeholder="e.g. 01712345678 or you@example.com"
                    className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={loading}
                  className="w-full rounded-md bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black text-xs uppercase tracking-wider h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)] border-none"
                >
                  {loading ? "Sending..." : "Send OTP Verification"}
                </Button>
              </form>
            )}

            {step === "VERIFY" && (
              <form onSubmit={handleVerify} className="space-y-4">
                {/* Countdown Timer */}
                <div className={`flex items-center justify-center gap-2 py-2 px-3 rounded-lg text-xs font-bold tracking-wider ${
                  timeLeft === 0
                    ? "bg-red-50 text-red-600 border border-red-200"
                    : timeLeft <= 60
                    ? "bg-amber-50 text-amber-600 border border-amber-200"
                    : "bg-zinc-50 text-zinc-600 border border-zinc-200"
                }`}>
                  <Clock className="w-3.5 h-3.5" />
                  {timeLeft === 0
                    ? "OTP Expired — request a new one"
                    : `OTP expires in ${formatTime(timeLeft)}`}
                </div>

                <div className="space-y-1">
                  <Label htmlFor="otp" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">OTP Code</Label>
                  <Input
                    id="otp"
                    ref={otpRef}
                    placeholder="Enter 6-digit code"
                    maxLength={6}
                    disabled={timeLeft === 0}
                    className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent text-center tracking-widest text-lg font-bold rounded-md"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={loading || timeLeft === 0}
                  className="w-full rounded-md bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black text-xs uppercase tracking-wider h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)] border-none disabled:opacity-50"
                >
                  {loading ? "Verifying..." : "Verify OTP Code"}
                </Button>
                <button
                  type="button"
                  onClick={() => setStep("REQUEST")}
                  className="w-full text-center text-xs text-zinc-500 hover:text-brand-accent transition-colors font-bold uppercase tracking-wider text-[10px]"
                >
                  {timeLeft === 0 ? "Request New OTP" : "Change phone/email"}
                </button>
              </form>
            )}

            {step === "SUBMIT" && (
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-1">
                  <Label htmlFor="password" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">New Password</Label>
                  <Input
                    id="password"
                    type="password"
                    ref={passwordRef}
                    placeholder="••••••••"
                    className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={loading}
                  className="w-full rounded-md bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black text-xs uppercase tracking-wider h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)] border-none"
                >
                  {loading ? "Submitting..." : "Update Password"}
                </Button>
              </form>
            )}

            <div className="text-center text-sm text-zinc-500 mt-4">
              Remember your password?{" "}
              <Link
                href="/login"
                onClick={(e) => {
                  e.preventDefault();
                  router.push("/login");
                }}
                className="font-bold text-brand-accent hover:text-brand-accent-hover transition-colors uppercase tracking-wider text-[10px]"
              >
                Sign In
              </Link>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
