import { useState } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { ArrowLeft, Eye, EyeOff, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { AmanahMark } from "@/components/brand/AmanahMark";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  requestPasswordOtp,
  resetPasswordWithOtp,
  verifyPasswordOtp,
  type AuthPlatform,
} from "@/lib/auth";

interface ForgotPasswordPageProps {
  platform: AuthPlatform;
}

type Step = "email" | "otp" | "reset";

export function ForgotPasswordPage({ platform }: ForgotPasswordPageProps) {
  const navigate = useNavigate();
  const [step, setStep] = useState<Step>("email");
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [demoOtp, setDemoOtp] = useState<string | null>(null);
  const [resetToken, setResetToken] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [resendSeconds, setResendSeconds] = useState(0);

  const isFirm = platform === "firm";
  const normalizedEmail = email.trim().toLowerCase();

  const titles: Record<Step, string> = {
    email: "Forgot password?",
    otp: "Enter verification code",
    reset: "Set a new password",
  };

  const subtitles: Record<Step, string> = {
    email: "Enter your account email and we’ll send a one-time password (OTP).",
    otp: `We sent a 6-digit code to ${normalizedEmail}. Enter it below to continue.`,
    reset: `Choose a new password for ${normalizedEmail}.`,
  };

  const startResendCooldown = () => {
    setResendSeconds(30);
    const timer = window.setInterval(() => {
      setResendSeconds((s) => {
        if (s <= 1) {
          window.clearInterval(timer);
          return 0;
        }
        return s - 1;
      });
    }, 1000);
  };

  const sendOtp = async () => {
    const result = await requestPasswordOtp(platform, email);
    if (!result.ok) {
      toast.error(result.error);
      return false;
    }

    if (result.emailed) {
      toast.success("OTP sent to your email");
    } else {
      toast.success("OTP generated");
    }
    setDemoOtp(result.demoOtp ?? null);
    startResendCooldown();
    return true;
  };

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const ok = await sendOtp();
    if (ok) setStep("otp");
    setLoading(false);
  };

  const handleResend = async () => {
    if (resendSeconds > 0 || loading) return;
    setLoading(true);
    setOtp("");
    await sendOtp();
    setLoading(false);
  };

  const handleOtpSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const result = await verifyPasswordOtp(platform, email, otp);
    if (!result.ok) {
      toast.error(result.error);
      setLoading(false);
      return;
    }
    setResetToken(result.resetToken);
    setStep("reset");
    toast.success("OTP verified");
    setLoading(false);
  };

  const handleResetSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }

    setLoading(true);
    const result = await resetPasswordWithOtp(platform, email, resetToken, password);
    if (!result.ok) {
      toast.error(result.error);
      setLoading(false);
      return;
    }

    toast.success("Password updated");
    navigate({ to: "/login", search: { reset: "success" } });
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4 py-12">
      <div className="w-full max-w-[420px]">
        <div className="mb-8 text-center">
          <AmanahMark size={56} className="mx-auto mb-5 shadow-[0_1px_3px_rgba(40,56,80,0.18)]" />
          <p className="font-display text-[26px] font-bold leading-none tracking-[0.1em] text-primary uppercase">
            Amanah
          </p>
          <p className="mt-2 text-[13px] font-medium text-brand">
            Boekhouding &amp; Belastingadvies
          </p>
          <p className="mt-3 inline-flex rounded-full bg-primary-soft px-2.5 py-0.5 text-[10px] font-bold tracking-[0.18em] text-primary uppercase">
            {isFirm ? "Firm" : "Client"}
          </p>
          <h1 className="mt-6 font-display text-[22px] font-semibold text-foreground">
            {titles[step]}
          </h1>
          <p className="mt-2 text-[14px] leading-relaxed text-muted-foreground">{subtitles[step]}</p>
        </div>

        {step === "email" && (
          <form
            onSubmit={handleEmailSubmit}
            className="rounded-xl border border-border bg-surface p-6 shadow-[0_1px_2px_rgba(40,56,80,0.05)]"
          >
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                autoComplete="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>

            <Button type="submit" className="mt-6 w-full" disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                  Sending OTP…
                </>
              ) : (
                "Send OTP"
              )}
            </Button>

            <p className="mt-4 text-center text-[13px] text-muted-foreground">
              <Link
                to="/login"
                className="inline-flex items-center gap-1 font-semibold text-primary hover:underline"
              >
                <ArrowLeft size={14} aria-hidden="true" />
                Back to sign in
              </Link>
            </p>
          </form>
        )}

        {step === "otp" && (
          <form
            onSubmit={handleOtpSubmit}
            className="rounded-xl border border-border bg-surface p-6 shadow-[0_1px_2px_rgba(40,56,80,0.05)]"
          >
            {demoOtp && (
              <div className="mb-4 rounded-lg border border-brand/30 bg-brand-soft px-3 py-2.5 text-[12.5px] text-brand-foreground">
                Prototype mode: email SMTP is not configured. Your OTP is{" "}
                <span className="font-bold tracking-[0.2em]">{demoOtp}</span>
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="otp">One-time password</Label>
              <Input
                id="otp"
                type="text"
                inputMode="numeric"
                autoComplete="one-time-code"
                placeholder="6-digit code"
                value={otp}
                onChange={(e) => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
                className="tracking-[0.35em]"
                maxLength={6}
                minLength={6}
                required
              />
            </div>

            <Button type="submit" className="mt-6 w-full" disabled={loading || otp.length < 6}>
              {loading ? (
                <>
                  <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                  Verifying…
                </>
              ) : (
                "Verify OTP"
              )}
            </Button>

            <div className="mt-4 flex flex-col items-center gap-2 text-[13px] text-muted-foreground">
              <button
                type="button"
                className="font-semibold text-primary hover:underline disabled:cursor-not-allowed disabled:opacity-50"
                onClick={handleResend}
                disabled={loading || resendSeconds > 0}
              >
                {resendSeconds > 0 ? `Resend OTP in ${resendSeconds}s` : "Resend OTP"}
              </button>
              <button
                type="button"
                className="inline-flex items-center gap-1 font-semibold text-primary hover:underline"
                onClick={() => {
                  setStep("email");
                  setOtp("");
                  setDemoOtp(null);
                  setResetToken("");
                }}
              >
                <ArrowLeft size={14} aria-hidden="true" />
                Use a different email
              </button>
            </div>
          </form>
        )}

        {step === "reset" && (
          <form
            onSubmit={handleResetSubmit}
            className="rounded-xl border border-border bg-surface p-6 shadow-[0_1px_2px_rgba(40,56,80,0.05)]"
          >
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="password">New password</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    autoComplete="new-password"
                    placeholder="At least 8 characters"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pr-10"
                    minLength={8}
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute top-1/2 right-2.5 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
                    aria-label={showPassword ? "Hide password" : "Show password"}
                  >
                    {showPassword ? (
                      <EyeOff size={16} aria-hidden="true" />
                    ) : (
                      <Eye size={16} aria-hidden="true" />
                    )}
                  </button>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="confirmPassword">Confirm new password</Label>
                <Input
                  id="confirmPassword"
                  type={showPassword ? "text" : "password"}
                  autoComplete="new-password"
                  placeholder="Repeat your new password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  minLength={8}
                  required
                />
              </div>
            </div>

            <Button type="submit" className="mt-6 w-full" disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                  Updating…
                </>
              ) : (
                "Reset password"
              )}
            </Button>
          </form>
        )}
      </div>
    </div>
  );
}
