"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Layers, RefreshCw } from "lucide-react";
import { ToolLayout } from "@/components/ToolLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";

const DNS_TYPES = ["A", "AAAA", "MX", "NS", "TXT", "CNAME", "SOA", "PTR", "SRV", "CAA"];

interface DnsData {
  domain: string;
  type: string;
  records: unknown[];
  count: number;
  error?: string;
}

function DnsLookupContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [domain, setDomain] = useState(searchParams.get("domain") ?? "");
  const [type, setType] = useState(searchParams.get("type") ?? "A");
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DnsData | null>(null);

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

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

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

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

  const formatRecord = (r: unknown): string => {
    if (typeof r === "string") return r;
    if (typeof r === "object" && r !== null) return JSON.stringify(r);
    return String(r);
  };

  return (
    <ToolLayout icon={Layers} title="DNS Lookup" description="Query DNS records by type for any domain.">
      <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, type)}
        />
        <Select value={type} onValueChange={(v) => { setType(v); updateUrl(domain, v); }}>
          <SelectTrigger className="w-24">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {DNS_TYPES.map((t) => <SelectItem key={t} value={t}>{t}</SelectItem>)}
          </SelectContent>
        </Select>
        <Button type="submit" disabled={loading}>
          {loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Lookup"}
        </Button>
      </form>

      {data && (
        <div className="glass-card rounded-xl animate-fade-up">
          <div className="px-4 py-3 border-b border-border/50 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="font-mono text-sm font-semibold">{data.domain}</span>
              <span className="badge-neutral px-2 py-0.5 rounded text-xs font-mono">{data.type}</span>
            </div>
            <span className="text-xs text-muted-foreground">{data.count} record{data.count !== 1 ? "s" : ""}</span>
          </div>

          {data.error ? (
            <div className="p-4 text-sm text-red-400">{data.error}</div>
          ) : data.records.length === 0 ? (
            <div className="p-4 text-sm text-muted-foreground">No records found</div>
          ) : (
            <div className="divide-y divide-border/50">
              {data.records.map((r, i) => (
                <div key={i} className="px-4 py-2.5 font-mono text-sm">
                  {formatRecord(r)}
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </ToolLayout>
  );
}

export default function DnsLookupPage() {
  return <Suspense><DnsLookupContent /></Suspense>;
}
