"use client";
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Globe, ExternalLink, RefreshCw, Shield, Server, Lock } 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 SiteData {
  url: string;
  finalUrl: string;
  status: number;
  title: string | null;
  description: string | null;
  ogImage: string | null;
  ogSiteName: string | null;
  themeColor: string | null;
  favicon: string | null;
  screenshotUrl: string;
  headers: Record<string, string | null>;
  error?: string;
}

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

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

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

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

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

  return (
    <ToolLayout icon={Globe} title="Site Preview" description="Fetch metadata, headers, and screenshot of any website.">
      <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" /> : "Preview"}
        </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">
          {/* Screenshot */}
          <div className="glass-card rounded-xl overflow-hidden">
            <div className="aspect-video bg-muted/30 relative">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={data.screenshotUrl}
                alt={data.title ?? "Site screenshot"}
                className="w-full h-full object-cover object-top"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = "none";
                }}
              />
            </div>
            <div className="p-4">
              <div className="flex items-start justify-between gap-3">
                <div className="flex items-center gap-2 min-w-0">
                  {data.favicon && (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={data.favicon} alt="" className="h-5 w-5 shrink-0 rounded" onError={(e) => { (e.target as HTMLElement).style.display = "none"; }} />
                  )}
                  <div className="min-w-0">
                    <p className="font-medium text-sm truncate">{data.title ?? data.finalUrl}</p>
                    <p className="text-xs text-muted-foreground truncate">{data.finalUrl}</p>
                  </div>
                </div>
                <a href={data.finalUrl} target="_blank" rel="noopener noreferrer">
                  <Button variant="ghost" size="icon" className="shrink-0">
                    <ExternalLink className="h-4 w-4" />
                  </Button>
                </a>
              </div>
              {data.description && <p className="text-xs text-muted-foreground mt-2 line-clamp-2">{data.description}</p>}
              {data.ogImage && (
                <div className="mt-3">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={data.ogImage} alt="OG Image" className="rounded-lg max-h-40 object-cover" onError={(e) => { (e.target as HTMLElement).style.display = "none"; }} />
                </div>
              )}
            </div>
          </div>

          {/* Headers */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">HTTP Headers</p>
            <div className="space-y-2">
              <Row label="Status" value={<Badge variant={data.status < 400 ? "ok" : "err"}>{data.status}</Badge>} />
              <Row label="Server" value={data.headers.server} />
              <Row label="X-Powered-By" value={data.headers.xPoweredBy} />
              <Row label="HSTS" value={data.headers.strictTransportSecurity ? <Badge variant="ok">Enabled</Badge> : <Badge variant="warn">Not set</Badge>} />
              <Row label="X-Frame-Options" value={data.headers.xFrameOptions ?? <Badge variant="warn">Not set</Badge>} />
              <Row label="CSP" value={data.headers.contentSecurityPolicy ? <Badge variant="ok">Present</Badge> : <Badge variant="warn">Not set</Badge>} />
            </div>
          </div>

          {/* Security */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Security</p>
            <div className="flex flex-wrap gap-2">
              <SecurityBadge icon={Lock} label="HTTPS" ok={data.finalUrl.startsWith("https")} />
              <SecurityBadge icon={Shield} label="HSTS" ok={!!data.headers.strictTransportSecurity} />
              <SecurityBadge icon={Server} label="CSP" ok={!!data.headers.contentSecurityPolicy} />
            </div>
          </div>
        </div>
      )}
    </ToolLayout>
  );
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  if (!value) return null;
  return (
    <div className="flex items-center justify-between gap-3 py-1.5 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>
  );
}

function SecurityBadge({ icon: Icon, label, ok }: { icon: React.ElementType; label: string; ok: boolean }) {
  return (
    <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium ${ok ? "badge-ok" : "badge-warn"}`}>
      <Icon className="h-3 w-3" />
      {label}
    </div>
  );
}

export default function SitePreviewPage() {
  return <Suspense><SitePreviewContent /></Suspense>;
}
