import { useState, useEffect } from "react";
import { DashboardTemplatePage } from "@/components/DashboardTemplatePage";
import { TemplateCard } from "@/components/templates/TemplateCard";
import { fetchLogoTemplates, type LogoTemplateDoc } from "@/services/logoTemplates";
import { Loader2, Search } from "lucide-react";
import { Input } from "@/components/ui/input";

export default function LogoTemplatesPage() {
  const [items, setItems] = useState<LogoTemplateDoc[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [debugRaw, setDebugRaw] = useState<string>("");

  useEffect(() => {
    (async () => {
      try {
        setLoading(true);
        // Fetch ALL (no filter) so private/unflagged docs still show while we verify
        const res = await fetchLogoTemplates({ pageSize: 50 });
        setItems(res.items);
        setDebugRaw(JSON.stringify(res.items.map(i => ({
          id: i.templateId, public: i.public, hasSVG: !!i.downloadURLs?.svg, hasRaster: !!i.downloadURLs?.raster,
          createdAt: i.createdAt?.toString?.() || typeof i.createdAt,
          updatedAt: i.updatedAt?.toString?.() || typeof i.updatedAt,
        })), null, 2));
      } catch (err) {
        console.error("Failed to load logo templates:", err);
        setDebugRaw(String(err));
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const filtered = items.filter((t) =>
    [t.name, t.description, ...(t.tags || [])]
      .filter(Boolean)
      .some((val) => val.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  return (
    <DashboardTemplatePage title="Logo Templates">
      <div className="space-y-6">
        <div className="bg-card p-6 rounded-lg border">
          <h2 className="text-xl font-semibold mb-2">Professional Logo Templates</h2>
          <p className="text-muted-foreground mb-4">
            Choose from our curated collection of professional logo templates. Customize colors,
            text, and positioning to match your brand.
          </p>
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-4 h-4" />
            <Input
              placeholder="Search templates..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>
        </div>

        {loading ? (
          <LoadingState />
        ) : filtered.length === 0 ? (
          <EmptyState />
        ) : (
          <>
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                {filtered.length} template{filtered.length !== 1 ? "s" : ""} available
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filtered.map((t) => {
                const previewUrl = t.downloadURLs?.svg || t.downloadURLs?.raster;
                const type = t.formats?.length
                  ? t.formats[0].toUpperCase()
                  : (t.downloadURLs?.svg ? "SVG" : t.downloadURLs?.raster ? "PNG/JPG" : "—");
                return (
                  <TemplateCard
                    key={t.templateId}
                    id={t.templateId}
                    name={t.name}
                    description={t.description}
                    tags={t.tags}
                    previewUrl={previewUrl}
                    source="firebase"
                    typeOverride={type}
                  />
                );
              })}
            </div>

            {/* Temporary debug: collapse via CSS if you want */}
            <pre className="text-xs text-gray-500 bg-gray-50 border rounded p-3 overflow-auto">{debugRaw}</pre>
          </>
        )}
      </div>
    </DashboardTemplatePage>
  );
}

function LoadingState() {
  return (
    <div className="flex items-center justify-center py-12">
      <div className="text-center">
        <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-muted-foreground" />
        <p className="text-muted-foreground">Loading templates...</p>
      </div>
    </div>
  );
}

function EmptyState() {
  return (
    <div className="text-center py-12">
      <p className="text-muted-foreground mb-2">No templates available yet</p>
      <p className="text-sm text-gray-500">Upload some logo templates from the admin panel to get started!</p>
    </div>
  );
}
