"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Ban, RefreshCw, CheckCircle2, XCircle } 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 CheckItem {
  blacklist: string;
  listed: boolean;
  response: string | null;
}

interface BlacklistData {
  target: string;
  isIP: boolean;
  lookupHost: string;
  checks: CheckItem[];
  listedCount: number;
  totalChecked: number;
  error?: string;
}

function BlacklistContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [target, setTarget] = useState(searchParams.get("target") ?? "");
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<BlacklistData | null>(null);

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

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

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

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

  const listed = data?.checks.filter((c) => c.listed) ?? [];
  const clean = data?.checks.filter((c) => !c.listed) ?? [];

  return (
    <ToolLayout icon={Ban} title="Blacklist Checker" description="Check if an IP or domain appears on email blacklists.">
      <form onSubmit={handleSubmit} className="flex gap-2 mb-6">
        <Input
          value={target}
          onChange={(e) => setTarget(e.target.value)}
          placeholder="IP address or domain"
          className="flex-1"
          onBlur={() => updateUrl(target)}
        />
        <Button type="submit" disabled={loading}>
          {loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Check"}
        </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">
          {/* Score */}
          <div className="glass-card rounded-xl p-5">
            <div className="flex items-center gap-5">
              <div className={`text-5xl font-bold ${listed.length === 0 ? "text-green-400" : listed.length <= 2 ? "text-yellow-400" : "text-red-400"}`}>
                {data.listedCount}
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Listed on</p>
                <p className="text-base font-medium">{data.listedCount} / {data.totalChecked} blacklists</p>
                <p className="text-xs text-muted-foreground mt-0.5">
                  {data.isIP ? "IPv4" : "Domain"}: {data.lookupHost}
                </p>
              </div>
              <div className="ml-auto">
                {listed.length === 0 ? (
                  <div className="flex items-center gap-2 badge-ok px-4 py-2 rounded-xl text-sm font-medium">
                    <CheckCircle2 className="h-5 w-5" /> Clean
                  </div>
                ) : (
                  <div className="flex items-center gap-2 badge-err px-4 py-2 rounded-xl text-sm font-medium">
                    <XCircle className="h-5 w-5" /> Listed
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Listed */}
          {listed.length > 0 && (
            <div className="glass-card rounded-xl overflow-hidden">
              <div className="px-4 py-3 border-b border-border/50 flex items-center gap-2">
                <XCircle className="h-4 w-4 text-red-400" />
                <p className="text-sm font-medium text-red-400">Listed ({listed.length})</p>
              </div>
              <div className="divide-y divide-border/50">
                {listed.map((item) => (
                  <div key={item.blacklist} className="flex items-center justify-between px-4 py-2.5">
                    <span className="text-sm font-mono">{item.blacklist}</span>
                    <span className="text-xs font-mono text-red-400">{item.response}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Clean */}
          <div className="glass-card rounded-xl overflow-hidden">
            <button
              className="w-full flex items-center justify-between px-4 py-3 border-b border-border/50 text-left"
              onClick={(e) => {
                const details = (e.currentTarget.nextSibling as HTMLElement);
                details.style.display = details.style.display === "none" ? "block" : "none";
              }}
            >
              <div className="flex items-center gap-2">
                <CheckCircle2 className="h-4 w-4 text-green-400" />
                <p className="text-sm font-medium text-green-400">Not listed ({clean.length})</p>
              </div>
              <span className="text-xs text-muted-foreground">Toggle</span>
            </button>
            <div style={{ display: "none" }}>
              <div className="divide-y divide-border/50">
                {clean.map((item) => (
                  <div key={item.blacklist} className="flex items-center px-4 py-2">
                    <span className="text-sm font-mono text-muted-foreground">{item.blacklist}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </ToolLayout>
  );
}

export default function BlacklistCheckerPage() {
  return <Suspense><BlacklistContent /></Suspense>;
}
