"use client";

import { useState } from "react";
import Link from "next/link";
import { ChevronDown, Eye, Loader2, Lock, Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  CATEGORY_META,
  NOTE_TEMPLATE_CATEGORIES,
  type NoteTemplate,
  type NoteTemplateCategory,
} from "@/lib/notes/note-templates";
import { formatCoverPrice } from "@/lib/notes/note-covers";
import { useNoteTemplates } from "@/hooks/use-note-templates";
import { useNoteDesignPurchases } from "@/hooks/use-note-design-purchases";
import { TemplatePreviewModal } from "@/components/notes/template-preview-modal";

interface NoteTemplateGalleryProps {
  onSelect: (templateId: string) => void;
  disabled?: boolean;
  compact?: boolean;
  // When true, the gallery starts folded down to just its header — used
  // where it sits above an already-populated note list, so it doesn't push
  // real notes below the fold. The empty-state usage leaves this off since
  // there's nothing else to see yet.
  collapsible?: boolean;
}

export function NoteTemplateGallery({ onSelect, disabled, compact, collapsible }: NoteTemplateGalleryProps) {
  const [activeCategory, setActiveCategory] = useState<NoteTemplateCategory | "all">("all");
  const [collapsed, setCollapsed] = useState(!!collapsible);
  const [previewTemplate, setPreviewTemplate] = useState<NoteTemplate | null>(null);
  const { allTemplates } = useNoteTemplates();
  const { ownsTemplate, purchaseTemplate, purchasingId } = useNoteDesignPurchases();

  const visibleTemplates = allTemplates.filter(
    (template) => activeCategory === "all" || template.category === activeCategory,
  );

  function handleClick(template: NoteTemplate) {
    if (ownsTemplate(template)) {
      onSelect(template.id);
    } else {
      void purchaseTemplate(template);
    }
  }

  return (
    <div className={cn("rounded-[22px] border border-white/[0.06] bg-white/[0.02]", compact ? "p-4" : "p-5")}>
      <div className={cn("flex flex-wrap items-center justify-between gap-3", !collapsed && "mb-3")}>
        <button
          type="button"
          onClick={() => collapsible && setCollapsed((v) => !v)}
          className={cn("flex items-center gap-2", collapsible && "cursor-pointer")}
        >
          <Sparkles className="h-3.5 w-3.5 text-teal-400/70" />
          <span className="text-[10px] font-bold uppercase tracking-[0.16em] text-white/30">
            Start from a template
          </span>
          {collapsible && (
            <ChevronDown className={cn("h-3.5 w-3.5 text-white/30 transition-transform", !collapsed && "rotate-180")} />
          )}
        </button>

        {/* Category filter */}
        {!collapsed && (
          <div className="flex flex-wrap items-center gap-1.5">
            <button
              onClick={() => setActiveCategory("all")}
              className={cn(
                "rounded-full px-2.5 py-1 text-[11px] font-semibold transition-all",
                activeCategory === "all"
                  ? "bg-white/[0.10] text-white/85"
                  : "text-white/35 hover:text-white/60",
              )}
            >
              All
            </button>
            {NOTE_TEMPLATE_CATEGORIES.map((category) => {
              const meta = CATEGORY_META[category];
              const active = activeCategory === category;
              return (
                <button
                  key={category}
                  onClick={() => setActiveCategory(category)}
                  className={cn(
                    "rounded-full px-2.5 py-1 text-[11px] font-semibold transition-all",
                    active ? cn(meta.accent, meta.text) : "text-white/35 hover:text-white/60",
                  )}
                >
                  {meta.label}
                </button>
              );
            })}
          </div>
        )}
      </div>

      {collapsed && (
        <p className="text-[11.5px] text-white/25">
          {allTemplates.length} templates — click to browse
        </p>
      )}

      {!collapsed && (
      <div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3 lg:grid-cols-5">
        {visibleTemplates.map((template) => {
          const meta = CATEGORY_META[template.category];
          const owned = ownsTemplate(template);
          const purchasing = purchasingId === template.id;
          return (
            <button
              key={template.id}
              onClick={() => handleClick(template)}
              disabled={disabled || purchasing}
              className={cn(
                "group relative flex flex-col gap-2 rounded-[16px] border bg-white/[0.02] p-3 text-left transition-all hover:bg-white/[0.045] disabled:opacity-40",
                "border-white/[0.06] hover:border-white/[0.12]",
              )}
            >
              <div className={cn("flex h-8 w-8 items-center justify-center rounded-full text-[15px]", meta.icon)}>
                {template.icon}
              </div>
              <div>
                <p className="text-[12.5px] font-semibold text-white/80">{template.name}</p>
                <p className="mt-0.5 line-clamp-2 text-[11px] leading-snug text-white/30">
                  {template.description}
                </p>
              </div>
              {!owned && (
                <div className="absolute right-2 top-2 flex items-center gap-1 rounded-full bg-black/60 px-2 py-0.5 text-[10px] font-semibold text-white">
                  {purchasing ? <Loader2 className="h-2.5 w-2.5 animate-spin" /> : <Lock className="h-2.5 w-2.5" />}
                  {formatCoverPrice(template.price)}
                </div>
              )}
              <span
                role="button"
                title="Preview"
                onClick={(e) => {
                  e.stopPropagation();
                  setPreviewTemplate(template);
                }}
                className="absolute left-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-black/55 text-white opacity-0 backdrop-blur-sm transition-opacity group-hover:opacity-100"
              >
                <Eye className="h-2.5 w-2.5" />
              </span>
            </button>
          );
        })}
      </div>
      )}

      <TemplatePreviewModal template={previewTemplate} open={!!previewTemplate} onClose={() => setPreviewTemplate(null)} />

      {!collapsed && (
        <Link
          href="/notes/marketplace?tab=templates"
          className="mt-3 flex items-center justify-center gap-1 border-t border-white/[0.06] pt-3 text-[11px] font-medium text-primary hover:underline"
        >
          <Sparkles className="h-3 w-3" />
          Template marketplace
        </Link>
      )}
    </div>
  );
}
