"use client";
import { Suspense, useState, useEffect, useCallback, useRef } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { KeyRound, Eye, EyeOff, Copy, CheckCircle2, RefreshCw } from "lucide-react";
import { ToolLayout } from "@/components/ToolLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";

interface MfaData {
  current: string;
  previous: string;
  next: string;
  remaining: number;
  step: number;
  timestamp: number;
}

function MfaViewerContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [secret, setSecret] = useState(searchParams.get("secret") ?? "");
  const [showSecret, setShowSecret] = useState(false);
  const [data, setData] = useState<MfaData | null>(null);
  const [remaining, setRemaining] = useState(0);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const refreshRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const updateUrl = useCallback((s: string) => {
    const params = new URLSearchParams();
    if (s) params.set("secret", s);
    router.replace(`/mfa-viewer${params.toString() ? `?${params}` : ""}`, { scroll: false });
  }, [router]);

  const fetchCode = useCallback(async (s: string) => {
    if (!s.trim()) return;
    setError(null);
    try {
      const res = await fetch(`/api/mfa?secret=${encodeURIComponent(s)}`);
      const json = await res.json();
      if (json.error) {
        setError(json.error);
        setData(null);
        return;
      }
      setData(json);
      setRemaining(json.remaining);
    } catch {
      setError("Request failed");
    }
  }, []);

  const startAutoRefresh = useCallback((s: string) => {
    if (refreshRef.current) clearInterval(refreshRef.current);
    if (intervalRef.current) clearInterval(intervalRef.current);

    fetchCode(s);

    // Countdown timer
    intervalRef.current = setInterval(() => {
      setRemaining((r) => {
        if (r <= 1) {
          fetchCode(s);
          return 30;
        }
        return r - 1;
      });
    }, 1000);
  }, [fetchCode]);

  useEffect(() => {
    const p = searchParams.get("secret");
    if (p) {
      setSecret(p);
      startAutoRefresh(p);
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
      if (refreshRef.current) clearInterval(refreshRef.current);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!secret.trim()) return;
    updateUrl(secret);
    startAutoRefresh(secret);
  };

  const copyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
    toast.success("Code copied!");
  };

  const progress = remaining / 30;
  const isUrgent = remaining <= 5;

  return (
    <ToolLayout icon={KeyRound} title="MFA Viewer" description="Generate TOTP codes from a base32 secret key. Codes refresh automatically.">
      <form onSubmit={handleSubmit} className="flex gap-2 mb-6">
        <div className="relative flex-1">
          <Input
            value={secret}
            onChange={(e) => setSecret(e.target.value.toUpperCase().replace(/\s/g, ""))}
            placeholder="JBSWY3DPEHPK3PXP"
            className="pr-9 font-mono"
            type={showSecret ? "text" : "password"}
            onBlur={() => updateUrl(secret)}
          />
          <button
            type="button"
            onClick={() => setShowSecret((v) => !v)}
            className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
          >
            {showSecret ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
          </button>
        </div>
        <Button type="submit">Generate</Button>
      </form>

      {error && <div className="result-box p-4 badge-err animate-fade-up">Error: {error}</div>}

      {data && !error && (
        <div className="space-y-4 animate-fade-up">
          {/* Main code */}
          <div className="glass-card rounded-xl p-6">
            <div className="flex items-center justify-between mb-4">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Current Code</p>
              <div className="flex items-center gap-2">
                <span className={`text-sm font-mono font-bold ${isUrgent ? "text-red-400" : remaining <= 10 ? "text-yellow-400" : "text-muted-foreground"}`}>
                  {remaining}s
                </span>
                <RefreshCw className={`h-3.5 w-3.5 text-muted-foreground ${remaining === 30 ? "animate-spin-once" : ""}`} />
              </div>
            </div>

            {/* Giant code display */}
            <div className="flex items-center justify-center gap-4 mb-5">
              <div
                className="flex items-center gap-2 cursor-pointer select-none"
                onClick={() => copyCode(data.current)}
              >
                <span className={`text-5xl font-mono font-bold tracking-[0.3em] transition-colors ${isUrgent ? "text-red-400" : "text-white"}`}>
                  {data.current.slice(0, 3)}
                </span>
                <span className="text-2xl text-muted-foreground/40">·</span>
                <span className={`text-5xl font-mono font-bold tracking-[0.3em] transition-colors ${isUrgent ? "text-red-400" : "text-white"}`}>
                  {data.current.slice(3)}
                </span>
              </div>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => copyCode(data.current)}
                className="shrink-0"
              >
                {copied ? <CheckCircle2 className="h-5 w-5 text-green-400" /> : <Copy className="h-5 w-5" />}
              </Button>
            </div>

            {/* Countdown bar */}
            <div className="relative h-1.5 bg-white/5 rounded-full overflow-hidden">
              <div
                className={`absolute left-0 top-0 h-full rounded-full transition-none ${isUrgent ? "bg-red-400" : remaining <= 10 ? "bg-yellow-400" : "bg-green-400"}`}
                style={{ width: `${progress * 100}%`, transition: "width 1s linear" }}
              />
            </div>
            <div className="flex justify-between text-[10px] text-muted-foreground mt-1">
              <span>Expires in {remaining}s</span>
              <span>Refreshes automatically</span>
            </div>
          </div>

          {/* Previous & Next */}
          <div className="grid grid-cols-2 gap-3">
            <div className="glass-card rounded-xl p-4 opacity-60">
              <p className="text-[10px] text-muted-foreground mb-2 uppercase tracking-wider">Previous</p>
              <p className="text-2xl font-mono font-bold tracking-widest">{data.previous}</p>
            </div>
            <div className="glass-card rounded-xl p-4 opacity-60">
              <p className="text-[10px] text-muted-foreground mb-2 uppercase tracking-wider">Next</p>
              <p className="text-2xl font-mono font-bold tracking-widest">{data.next}</p>
            </div>
          </div>

          {/* Info */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Info</p>
            <div className="space-y-2">
              <Row label="Algorithm" value="TOTP (RFC 6238)" />
              <Row label="Step" value="30 seconds" />
              <Row label="Digits" value="6" />
              <Row label="Hash" value="HMAC-SHA1" />
              <Row label="Timestamp" value={new Date(data.timestamp * 1000).toISOString()} />
            </div>
          </div>
        </div>
      )}

      {/* Instructions if empty */}
      {!data && !error && (
        <div className="glass-card rounded-xl p-8 text-center">
          <KeyRound className="h-10 w-10 text-muted-foreground/30 mx-auto mb-3" />
          <p className="text-sm text-muted-foreground">Enter your base32 TOTP secret above.</p>
          <p className="text-xs text-muted-foreground/60 mt-1">The secret is typically found in your authenticator app setup (QR code backup).</p>
          <p className="text-xs text-muted-foreground/40 mt-3 font-mono">Example: JBSWY3DPEHPK3PXP</p>
        </div>
      )}
    </ToolLayout>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex justify-between py-1 border-b border-border/50 last:border-0">
      <span className="text-xs text-muted-foreground">{label}</span>
      <span className="text-xs font-mono">{value}</span>
    </div>
  );
}

export default function MfaViewerPage() {
  return <Suspense><MfaViewerContent /></Suspense>;
}
