"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { requestAdminOtp, verifyAdminOtp } from "@/lib/actions/admin-auth";
import { useEffect, useState, useCallback } from "react";

/** True when a thrown error is Next's internal redirect signal. */
function isRedirectError(error: unknown): boolean {
  return (
    typeof error === "object" &&
    error !== null &&
    "digest" in error &&
    String((error as { digest?: unknown }).digest).startsWith("NEXT_")
  );
}

function LoginForm() {
  const [isOtp, setIsOtp] = useState(false);
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [loading, setLoading] = useState(false);
  const [resendCooldown, setResendCooldown] = useState(0);

  // Tick down the resend cooldown once per second.
  useEffect(() => {
    if (resendCooldown <= 0) return;
    const t = setTimeout(() => setResendCooldown((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [resendCooldown]);

  const handleEmailSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError("");
      setSuccess("");

      const trimmed = email.trim().toLowerCase();
      if (!trimmed) {
        setError("Email is required");
        return;
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
        setError("Please enter a valid email address");
        return;
      }

      setLoading(true);
      try {
        const result = await requestAdminOtp(trimmed);
        if (result.success) {
          setIsOtp(true);
          setOtp("");
          setSuccess(result.message ?? "A verification code was sent to your email.");
          setResendCooldown(result.resendIn ?? 60);
        } else {
          setError(result.error ?? "Failed to send OTP");
        }
      } catch {
        setError("An unexpected error occurred");
      } finally {
        setLoading(false);
      }
    },
    [email],
  );

  const handleOtpSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError("");
      setSuccess("");

      if (otp.length !== 6) {
        setError("Please enter the complete 6-digit code");
        return;
      }

      setLoading(true);
      try {
        // verifyAdminOtp validates the admin email on the server, creates the
        // session (cookie persisted via nextCookies), and redirects server-side.
        await verifyAdminOtp(email.trim().toLowerCase(), otp);
        // Only reached if a redirect didn't take over (e.g. already handled).
        setSuccess("Verified. Opening the admin dashboard...");
      } catch (err) {
        if (isRedirectError(err)) return; // Next.js is navigating — leave it.
        setError(
          typeof err === "object" &&
            err !== null &&
            "error" in err &&
            typeof (err as { error?: unknown }).error === "string"
            ? (err as { error: string }).error
            : "An unexpected error occurred",
        );
      } finally {
        setLoading(false);
      }
    },
    [email, otp],
  );

  const handleResend = useCallback(async () => {
    if (resendCooldown > 0 || loading) return;
    setError("");
    setSuccess("");
    setLoading(true);
    try {
      const result = await requestAdminOtp(email.trim().toLowerCase());
      if (result.success) {
        setOtp("");
        setError("");
        setSuccess("A new verification code was sent to your email.");
        setResendCooldown(result.resendIn ?? 60);
      } else {
        setError(result.error ?? "Failed to resend the code");
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  }, [email, loading, resendCooldown]);

  return (
    <div className="w-full">
      {error && (
        <div
          role="alert"
          className="mb-3 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive"
        >
          {error}
        </div>
      )}
      {success && !error && (
        <div
          role="status"
          className="mb-3 rounded-md bg-emerald-500/10 px-3 py-2 text-xs text-emerald-700 dark:text-emerald-400"
        >
          {success}
        </div>
      )}

      {!isOtp ? (
        <form onSubmit={handleEmailSubmit} className="w-full space-y-2">
          <div className="justify-center items-center flex">
            <Input
              id="email-input"
              type="email"
              placeholder="Enter your email address"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              disabled={loading}
            />
          </div>
          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "Sending code..." : "Continue With Email"}
          </Button>
        </form>
      ) : (
        <form onSubmit={handleOtpSubmit} className="w-full space-y-4">
          <p className="text-center text-xs text-muted-foreground">
            Enter the 6-digit code sent to{" "}
            <span className="font-medium text-foreground">{email}</span>
          </p>
          <div className="justify-center items-center flex">
            <InputOTP
              className="w-full"
              maxLength={6}
              value={otp}
              onChange={setOtp}
              autoFocus
            >
              <InputOTPGroup>
                <InputOTPSlot index={0} />
                <InputOTPSlot index={1} />
                <InputOTPSlot index={2} />
              </InputOTPGroup>
              <InputOTPSeparator />
              <InputOTPGroup>
                <InputOTPSlot index={3} />
                <InputOTPSlot index={4} />
                <InputOTPSlot index={5} />
              </InputOTPGroup>
            </InputOTP>
          </div>
          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "Verifying..." : "Verify & Login"}
          </Button>
          <div className="flex items-center justify-between gap-2">
            <Button
              type="button"
              variant="ghost"
              className="text-xs"
              disabled={loading || resendCooldown > 0}
              onClick={handleResend}
            >
              {resendCooldown > 0
                ? `Resend code in ${resendCooldown}s`
                : "Resend code"}
            </Button>
            <Button
              type="button"
              variant="ghost"
              className="text-xs"
              disabled={loading}
              onClick={() => {
                setIsOtp(false);
                setOtp("");
                setError("");
                setSuccess("");
                setResendCooldown(0);
              }}
            >
              Use a different email
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}

export default LoginForm;