"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { ArrowRightLeft, RefreshCw, ArrowRight, Clock } 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 Hop {
  step: number;
  url: string;
  status: number;
  statusText: string;
  location: string | null;
  timing: number;
}

interface RedirectData {
  original: string;
  hops: Hop[];
  final: string;
  error?: string;
}

function RedirectCheckContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [url, setUrl] = useState(searchParams.get("url") ?? "");
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<RedirectData | null>(null);

  const updateUrl = useCallback((v: string) => {
    const params = new URLSearchParams();
    if (v) params.set("url", v);
    router.replace(`/redirect-check${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/redirect-check?url=${encodeURIComponent(v)}`);
      const json = await res.json();
      setData(json);
    } catch {
      toast.error("Request failed");
    } finally {
      setLoading(false);
    }
  }, []);

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

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

  const statusBadge = (code: number) => {
    if (code >= 200 && code < 300) return <Badge variant="ok">{code}</Badge>;
    if (code >= 300 && code < 400) return <Badge variant="warn">{code}</Badge>;
    return <Badge variant="err">{code}</Badge>;
  };

  const totalTime = data?.hops.reduce((s, h) => s + h.timing, 0);

  return (
    <ToolLayout icon={ArrowRightLeft} title="Redirect Check" description="Trace the full HTTP redirect chain for any URL.">
      <form onSubmit={handleSubmit} className="flex gap-2 mb-6">
        <Input
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          placeholder="https://example.com"
          className="flex-1"
          onBlur={() => updateUrl(url)}
        />
        <Button type="submit" disabled={loading}>
          {loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Check"}
        </Button>
      </form>

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

      {data && data.hops.length > 0 && (
        <div className="space-y-4 animate-fade-up">
          {/* Summary */}
          <div className="glass-card rounded-xl p-4 flex items-center gap-4">
            <div className="text-center">
              <p className="text-2xl font-bold">{data.hops.length}</p>
              <p className="text-xs text-muted-foreground">hops</p>
            </div>
            <div className="w-px h-10 bg-border" />
            <div className="text-center">
              <p className="text-2xl font-bold">{totalTime}ms</p>
              <p className="text-xs text-muted-foreground">total</p>
            </div>
            <div className="w-px h-10 bg-border" />
            <div className="flex-1 min-w-0">
              <p className="text-xs text-muted-foreground mb-0.5">Final URL</p>
              <p className="text-sm font-mono truncate">{data.final}</p>
            </div>
          </div>

          {/* Chain */}
          <div className="glass-card rounded-xl divide-y divide-border/50">
            {data.hops.map((hop, i) => (
              <div key={i} className="p-4">
                <div className="flex items-start gap-3">
                  <div className="flex flex-col items-center gap-1 shrink-0">
                    <div className="h-6 w-6 rounded-full bg-white/8 flex items-center justify-center text-xs font-bold">{hop.step}</div>
                    {i < data.hops.length - 1 && <div className="w-px flex-1 bg-border min-h-[16px]" />}
                  </div>
                  <div className="flex-1 min-w-0 pb-1">
                    <div className="flex items-center gap-2 flex-wrap mb-1">
                      {statusBadge(hop.status)}
                      <span className="text-xs text-muted-foreground">{hop.statusText}</span>
                      <span className="flex items-center gap-0.5 text-xs text-muted-foreground ml-auto">
                        <Clock className="h-3 w-3" />{hop.timing}ms
                      </span>
                    </div>
                    <p className="text-sm font-mono truncate text-foreground/80">{hop.url}</p>
                    {hop.location && (
                      <div className="flex items-center gap-1.5 mt-1.5 text-xs text-muted-foreground">
                        <ArrowRight className="h-3 w-3 shrink-0" />
                        <span className="font-mono truncate">{hop.location}</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>

          {data.error && (
            <div className="result-box p-3 badge-warn text-xs">{data.error}</div>
          )}
        </div>
      )}
    </ToolLayout>
  );
}

export default function RedirectCheckPage() {
  return <Suspense><RedirectCheckContent /></Suspense>;
}
