"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Search, RefreshCw, Calendar, Globe, Shield } from "lucide-react";
import { ToolLayout } from "@/components/ToolLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";

interface WhoisData {
  domain: string;
  parsed: {
    domainName: string;
    registrar: string | null;
    registrarUrl: string | null;
    createdDate: string | null;
    updatedDate: string | null;
    expiryDate: string | null;
    status: string[];
    nameservers: string[];
    dnssec: string | null;
    registrantName: string | null;
    registrantCountry: string | null;
    adminEmail: string | null;
  };
  raw: string;
  error?: string;
}

function WhoisContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [domain, setDomain] = useState(searchParams.get("domain") ?? "");
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<WhoisData | null>(null);
  const [showRaw, setShowRaw] = useState(false);

  const updateUrl = useCallback((d: string) => {
    const params = new URLSearchParams();
    if (d) params.set("domain", d);
    router.replace(`/whois${params.toString() ? `?${params}` : ""}`, { scroll: false });
  }, [router]);

  const lookup = useCallback(async (d: string) => {
    if (!d.trim()) return;
    setLoading(true);
    setData(null);
    try {
      const res = await fetch(`/api/whois?domain=${encodeURIComponent(d)}`);
      const json = await res.json();
      setData(json);
    } catch {
      toast.error("Request failed");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const p = searchParams.get("domain");
    if (p) { setDomain(p); lookup(p); }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); updateUrl(domain); lookup(domain); };

  const formatDate = (d: string | null) => {
    if (!d) return null;
    try { return new Date(d).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" }); }
    catch { return d; }
  };

  const isExpiringSoon = (d: string | null) => {
    if (!d) return false;
    const days = (new Date(d).getTime() - Date.now()) / 86400000;
    return days > 0 && days < 60;
  };

  const isExpired = (d: string | null) => {
    if (!d) return false;
    return new Date(d) < new Date();
  };

  return (
    <ToolLayout icon={Search} title="WHOIS Lookup" description="Domain registration, ownership, and expiry info.">
      <form onSubmit={handleSubmit} className="flex gap-2 mb-6">
        <Input
          value={domain}
          onChange={(e) => setDomain(e.target.value)}
          placeholder="example.com"
          className="flex-1"
          onBlur={() => updateUrl(domain)}
        />
        <Button type="submit" disabled={loading}>
          {loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Lookup"}
        </Button>
      </form>

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

      {data && !data.error && (
        <div className="space-y-4 animate-fade-up">
          {/* Key info card */}
          <div className="glass-card rounded-xl p-5">
            <div className="flex items-start justify-between gap-3 mb-4">
              <div>
                <p className="text-lg font-semibold">{data.parsed.domainName}</p>
                {data.parsed.registrar && <p className="text-sm text-muted-foreground">{data.parsed.registrar}</p>}
              </div>
              <div className="flex flex-wrap gap-1.5">
                {data.parsed.expiryDate && (
                  <Badge variant={isExpired(data.parsed.expiryDate) ? "err" : isExpiringSoon(data.parsed.expiryDate) ? "warn" : "ok"}>
                    {isExpired(data.parsed.expiryDate) ? "Expired" : isExpiringSoon(data.parsed.expiryDate) ? "Expiring Soon" : "Active"}
                  </Badge>
                )}
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <DateCard icon={Calendar} label="Created" date={formatDate(data.parsed.createdDate)} />
              <DateCard icon={Calendar} label="Updated" date={formatDate(data.parsed.updatedDate)} />
              <DateCard
                icon={Calendar}
                label="Expires"
                date={formatDate(data.parsed.expiryDate)}
                warn={isExpiringSoon(data.parsed.expiryDate)}
                danger={isExpired(data.parsed.expiryDate)}
              />
            </div>
          </div>

          {/* Registrant */}
          {(data.parsed.registrantName || data.parsed.registrantCountry || data.parsed.adminEmail) && (
            <div className="glass-card rounded-xl p-4">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Registrant</p>
              <div className="space-y-1.5">
                {data.parsed.registrantName && <Row label="Name / Org" value={data.parsed.registrantName} />}
                {data.parsed.registrantCountry && <Row label="Country" value={data.parsed.registrantCountry} />}
                {data.parsed.adminEmail && <Row label="Admin Email" value={data.parsed.adminEmail} />}
              </div>
            </div>
          )}

          {/* Nameservers */}
          {data.parsed.nameservers.length > 0 && (
            <div className="glass-card rounded-xl p-4">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Nameservers</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
                {data.parsed.nameservers.map((ns) => (
                  <div key={ns} className="flex items-center gap-2">
                    <Globe className="h-3 w-3 text-muted-foreground shrink-0" />
                    <span className="text-sm font-mono">{ns}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Status */}
          {data.parsed.status.length > 0 && (
            <div className="glass-card rounded-xl p-4">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Domain Status</p>
              <div className="flex flex-wrap gap-1.5">
                {data.parsed.status.map((s) => (
                  <Badge key={s} variant="neutral" className="text-[10px]">{s.split(" ")[0]}</Badge>
                ))}
              </div>
              {data.parsed.dnssec && (
                <div className="flex items-center gap-2 mt-3">
                  <Shield className="h-3.5 w-3.5 text-muted-foreground" />
                  <span className="text-sm">DNSSEC: <span className="text-foreground">{data.parsed.dnssec}</span></span>
                </div>
              )}
            </div>
          )}

          {/* Raw */}
          <div className="glass-card rounded-xl">
            <button onClick={() => setShowRaw((v) => !v)} className="w-full flex items-center justify-between px-4 py-3 text-xs text-muted-foreground hover:text-foreground transition-colors">
              <span className="font-semibold uppercase tracking-wider text-muted-foreground/60">Raw WHOIS</span>
              <span>{showRaw ? "Hide" : "Show"}</span>
            </button>
            {showRaw && <pre className="result-box p-4 text-[11px] overflow-x-auto max-h-96">{data.raw}</pre>}
          </div>
        </div>
      )}
    </ToolLayout>
  );
}

function DateCard({ icon: Icon, label, date, warn, danger }: { icon: React.ElementType; label: string; date: string | null; warn?: boolean; danger?: boolean }) {
  return (
    <div className="bg-muted/30 rounded-lg p-3">
      <div className="flex items-center gap-1.5 mb-1">
        <Icon className="h-3 w-3 text-muted-foreground" />
        <span className="text-xs text-muted-foreground">{label}</span>
      </div>
      <p className={`text-sm font-medium ${danger ? "text-red-400" : warn ? "text-yellow-400" : ""}`}>
        {date ?? "—"}
      </p>
    </div>
  );
}

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

export default function WhoisPage() {
  return <Suspense><WhoisContent /></Suspense>;
}
