"use client";

/**
 * "Free Images" tab for Image Library — search Unsplash/Pexels for
 * copyright-free stock photos.
 */

import { useCallback, useState } from "react";
import { Search, Loader2, ImageIcon, Camera } from "lucide-react";

interface FreeImage {
  id: string; url: string; thumbnailUrl: string; altText: string;
  photographer: string; source: string; downloadUrl: string;
  width: number; height: number;
}

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

export default function FreeImagesTab({ brandId, onSelect }: Props) {
  const [query, setQuery] = useState("");
  const [images, setImages] = useState<FreeImage[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [source, setSource] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const doSearch = useCallback(async (q: string, p: number, append: boolean) => {
    if (!q.trim()) return;
    setLoading(true); setMessage(null);
    try {
      const res = await fetch(`/api/page-studio/free-images?query=${encodeURIComponent(q)}&page=${p}`);
      const data = await res.json();
      if (data.message) setMessage(data.message);
      const newImages = data.images || [];
      setImages(append ? (prev) => [...prev, ...newImages] : newImages);
      setSource(data.source);
      setHasMore(newImages.length >= 15);
      setPage(p);
    } catch {
      setMessage("Search failed");
    } finally { setLoading(false); }
  }, []);

  const handleSearch = () => { doSearch(query, 1, false); };
  const loadMore = () => { doSearch(query, page + 1, true); };

  const handleKey = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") handleSearch();
  };

  // Store as BrandAsset when selected (download to self-host)
  const handleSelect = useCallback(async (img: FreeImage) => {
    // First let them use the image directly (fast path)
    onSelect(img.url, img.altText);

    // Fire-and-forget: save as brand asset for self-hosting
    fetch(`/api/brands/${brandId}/assets`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        externalUrl: img.downloadUrl || img.url,
        filename: `${img.source}-${img.id}.jpg`,
        altText: img.altText,
        type: "photo",
        attribution: `Photo by ${img.photographer} on ${img.source}`,
      }),
    }).catch(() => { /* non-critical */ });
  }, [brandId, onSelect]);

  return (
    <div>
      {/* Search bar */}
      <div className="flex items-center gap-2 mb-4">
        <div className="relative flex-1">
          <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={handleKey}
            placeholder="Search free images…"
            className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500"
          />
        </div>
        <button onClick={handleSearch} disabled={loading || !query.trim()}
          className="px-4 py-2 bg-slate-900 text-white text-xs font-semibold rounded-lg hover:bg-slate-800 disabled:opacity-50">
          {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : "Search"}
        </button>
      </div>

      {/* Message / empty state */}
      {message && images.length === 0 && (
        <div className="text-center py-12">
          <Camera className="w-10 h-10 mx-auto mb-3 text-slate-200" />
          <p className="text-sm font-semibold text-slate-600 mb-1">Free Image Search</p>
          <p className="text-xs text-slate-500">{message}</p>
        </div>
      )}

      {!message && images.length === 0 && !loading && (
        <div className="text-center py-12">
          <ImageIcon className="w-10 h-10 mx-auto mb-3 text-slate-200" />
          <p className="text-sm font-semibold text-slate-600 mb-1">Search for free stock photos</p>
          <p className="text-xs text-slate-500">Results from {source || "Unsplash or Pexels"} — free for commercial use</p>
        </div>
      )}

      {/* Results grid */}
      {images.length > 0 && (
        <>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
            {images.map((img) => (
              <div key={img.id} className="group relative rounded-xl border border-slate-200 overflow-hidden bg-white hover:border-slate-400 hover:shadow-md transition-all">
                <button onClick={() => handleSelect(img)} className="block w-full aspect-[4/3] bg-slate-50 flex items-center justify-center">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={img.thumbnailUrl} alt={img.altText} className="w-full h-full object-cover" loading="lazy" />
                </button>
                <div className="px-2.5 py-2 border-t border-slate-100 text-left">
                  <p className="text-[10px] text-slate-500 truncate">
                    <Camera className="w-2.5 h-2.5 inline mr-0.5" />
                    {img.photographer} <span className="text-slate-300">on</span>{" "}
                    <span className="capitalize">{img.source}</span>
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Load more */}
          {hasMore && (
            <div className="text-center mt-4">
              <button onClick={loadMore} disabled={loading}
                className="px-4 py-2 text-xs font-semibold text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50">
                {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin inline mr-1" /> : null}
                Load More
              </button>
            </div>
          )}
        </>
      )}

      {loading && images.length > 0 && (
        <div className="flex justify-center py-4"><Loader2 className="w-4 h-4 animate-spin text-slate-400" /></div>
      )}
    </div>
  );
}
