"use client";

/**
 * "From Website" tab for Image Library — scans the brand's website for images.
 */

import { useCallback, useState } from "react";
import { Globe, Loader2, ImageIcon, Filter } from "lucide-react";

interface ScrapedImage {
  url: string; altText: string; width: number | null; height: number | null;
  category: string; sourcePage: string;
}

interface Props {
  brandId: string;
  onSelect: (url: string, alt: string) => void;
}

const CATEGORIES = ["all", "hero", "product", "team", "logo", "background", "other"] as const;

export default function WebsiteImagesTab({ brandId, onSelect }: Props) {
  const [images, setImages] = useState<ScrapedImage[]>([]);
  const [loading, setLoading] = useState(false);
  const [scanned, setScanned] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [domain, setDomain] = useState<string | null>(null);
  const [category, setCategory] = useState<string>("all");

  const scan = useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const res = await fetch("/api/page-studio/scrape-images", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Scan failed");
      setImages(data.images || []);
      setDomain(data.domain || null);
      setScanned(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Scan failed");
    } finally { setLoading(false); }
  }, [brandId]);

  const filtered = category === "all" ? images : images.filter((i) => i.category === category);

  if (!scanned && !loading) {
    return (
      <div className="flex flex-col items-center justify-center py-16">
        <Globe className="w-10 h-10 text-slate-300 mb-3" />
        <p className="text-sm font-semibold text-slate-700 mb-1">Scan your website for images</p>
        <p className="text-xs text-slate-500 mb-4">We&apos;ll extract usable images from your top pages</p>
        <button onClick={scan} className="px-4 py-2 bg-slate-900 text-white text-xs font-semibold rounded-lg hover:bg-slate-800">
          Scan Website
        </button>
        {error && <p className="mt-3 text-xs text-red-600">{error}</p>}
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-16">
        <Loader2 className="w-6 h-6 animate-spin text-slate-400 mb-3" />
        <p className="text-sm font-semibold text-slate-600">Scanning {domain || "website"} for images…</p>
        <p className="text-xs text-slate-400 mt-1">This may take 10–15 seconds</p>
      </div>
    );
  }

  return (
    <div>
      {/* Category filter */}
      <div className="flex items-center gap-2 mb-4">
        <Filter className="w-3.5 h-3.5 text-slate-400" />
        <div className="flex gap-1 flex-wrap">
          {CATEGORIES.map((c) => (
            <button key={c} onClick={() => setCategory(c)}
              className={`px-2.5 py-1 text-[11px] font-semibold rounded-md capitalize transition-colors ${
                category === c ? "bg-slate-900 text-white" : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}>{c === "all" ? "All" : c}</button>
          ))}
        </div>
        <button onClick={scan} className="ml-auto text-[11px] font-semibold text-slate-500 hover:text-slate-700">Rescan</button>
      </div>

      {filtered.length === 0 ? (
        <div className="text-center py-12">
          <ImageIcon className="w-8 h-8 mx-auto mb-2 text-slate-200" />
          <p className="text-xs text-slate-500">{images.length === 0 ? "No images found on website" : "No images in this category"}</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
          {filtered.map((img, i) => (
            <div key={i} className="group relative rounded-xl border border-slate-200 overflow-hidden bg-white hover:border-slate-400 hover:shadow-md transition-all">
              <button onClick={() => onSelect(img.url, img.altText)} className="block w-full aspect-square bg-slate-50 flex items-center justify-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={img.url} alt={img.altText} className="max-w-full max-h-full object-contain" loading="lazy" />
              </button>
              <div className="px-2.5 py-2 border-t border-slate-100 text-left">
                <p className="text-[11px] font-semibold text-slate-700 truncate">{img.altText || "No alt text"}</p>
                <div className="flex items-center justify-between mt-0.5">
                  <span className="text-[10px] text-slate-400 capitalize">{img.category}</span>
                  {img.width && img.height && (
                    <span className="text-[9px] font-mono text-slate-400">{img.width}×{img.height}</span>
                  )}
                </div>
                <p className="text-[9px] text-slate-300 truncate mt-0.5">{img.sourcePage.replace(/^https?:\/\//, "")}</p>
              </div>
              <div className="absolute inset-0 bg-slate-900/0 group-hover:bg-slate-900/5 transition-colors pointer-events-none" />
            </div>
          ))}
        </div>
      )}
      {error && <p className="mt-3 text-xs text-red-600">{error}</p>}
    </div>
  );
}
