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("");

  useEffect(() => {
    const loadTemplates = async () => {
      try {
        setLoading(true);
        const { items } = await fetchLogoTemplates({ onlyPublic: true, pageSize: 50 });
        setItems(items);
      } catch (err) {
        console.error("Failed to load logo templates:", err);
      } finally {
        setLoading(false);
      }
    };
    loadTemplates();
  }, []);

  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">
        {/* Header Section */}
        <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>

          {/* Search */}
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 transform -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>

        {/* Templates Grid */}
        {loading ? (
          <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>
        ) : filtered.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-muted-foreground mb-2">
              {searchTerm
                ? `No templates found for "${searchTerm}"`
                : "No templates available yet"}
            </p>
            {searchTerm ? (
              <button
                onClick={() => setSearchTerm("")}
                className="text-sm text-blue-600 hover:text-blue-700"
              >
                Clear search
              </button>
            ) : (
              <p className="text-sm text-gray-500">
                Upload some logo templates from the admin panel to get started!
              </p>
            )}
          </div>
        ) : (
          <>
            <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?.join(", ").toUpperCase() || "—";
                return (
                  <TemplateCard
                    key={t.templateId}
                    id={t.templateId}
                    name={t.name}
                    description={t.description}
                    tags={[...(t.tags || []), type]}
                    previewUrl={previewUrl}
                    source="firebase"
                  />
                );
              })}
            </div>
          </>
        )}
      </div>
    </DashboardTemplatePage>
  );
}
