"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { MapPin, RefreshCw, Wifi } 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 IpData {
  ip: string;
  city: string;
  region: string;
  country: string;
  country_code: string;
  postal: string;
  latitude: number;
  longitude: number;
  timezone: string;
  org: string;
  asn: string;
  isp: string;
  is_vpn?: boolean;
  is_datacenter?: boolean;
  error?: string;
}

function IpLookupContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [ip, setIp] = useState(searchParams.get("ip") ?? "");
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<IpData | null>(null);

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

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

  useEffect(() => {
    const p = searchParams.get("ip");
    if (p) { setIp(p); lookup(p); }
    else lookup(""); // Look up requester IP
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  return (
    <ToolLayout icon={MapPin} title="IP Lookup" description="Geolocation and ASN info for any IP address.">
      <form onSubmit={handleSubmit} className="flex gap-2 mb-6">
        <Input
          value={ip}
          onChange={(e) => setIp(e.target.value)}
          placeholder="Leave empty for your IP"
          className="flex-1"
          onBlur={() => updateUrl(ip)}
        />
        <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">
          {/* Main card */}
          <div className="glass-card rounded-xl p-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="h-10 w-10 rounded-xl bg-white/8 border border-white/10 flex items-center justify-center">
                <Wifi className="h-5 w-5" />
              </div>
              <div>
                <p className="text-xl font-mono font-bold">{data.ip}</p>
                <p className="text-sm text-muted-foreground">{data.isp ?? data.org}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <InfoCard label="City" value={data.city} />
              <InfoCard label="Region" value={data.region} />
              <InfoCard label="Country" value={`${data.country} (${data.country_code})`} />
              <InfoCard label="Postal" value={data.postal} />
              <InfoCard label="Timezone" value={data.timezone} />
              <InfoCard label="Coordinates" value={data.latitude && data.longitude ? `${data.latitude.toFixed(4)}, ${data.longitude.toFixed(4)}` : undefined} />
            </div>
          </div>

          {/* Network */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Network</p>
            <div className="space-y-2">
              <Row label="ASN" value={data.asn} />
              <Row label="Organization" value={data.org} />
              <Row label="ISP" value={data.isp} />
              {data.is_vpn !== undefined && <Row label="VPN/Proxy" value={data.is_vpn ? "Detected" : "Not detected"} />}
              {data.is_datacenter !== undefined && <Row label="Datacenter" value={data.is_datacenter ? "Yes" : "No"} />}
            </div>
          </div>

          {/* Map link */}
          {data.latitude && data.longitude && (
            <a
              href={`https://www.openstreetmap.org/?mlat=${data.latitude}&mlon=${data.longitude}#map=12/${data.latitude}/${data.longitude}`}
              target="_blank"
              rel="noopener noreferrer"
              className="glass-card rounded-xl p-3 flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <MapPin className="h-4 w-4" />
              View on OpenStreetMap — {data.latitude.toFixed(4)}, {data.longitude.toFixed(4)}
            </a>
          )}
        </div>
      )}
    </ToolLayout>
  );
}

function InfoCard({ label, value }: { label: string; value: string | null | undefined }) {
  if (!value) return null;
  return (
    <div className="bg-muted/30 rounded-lg p-2.5">
      <p className="text-[10px] text-muted-foreground mb-0.5">{label}</p>
      <p className="text-sm font-medium">{value}</p>
    </div>
  );
}

function Row({ label, value }: { label: string; value: string | null | undefined }) {
  if (!value) return null;
  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 shrink-0">{label}</span>
      <span className="text-xs text-right">{value}</span>
    </div>
  );
}

export default function IpLookupPage() {
  return <Suspense><IpLookupContent /></Suspense>;
}
