"use client";

import { create } from "zustand";
import type { NoteTemplate, NoteTemplateCategory } from "@/lib/notes/note-templates";

interface NoteTemplateRow {
  id: string;
  creator_id: string;
  name: string;
  description: string;
  category: string;
  icon: string;
  price_cents: number;
  content: Record<string, unknown>;
}

function rowToTemplate(row: NoteTemplateRow): NoteTemplate {
  return {
    id: row.id,
    name: row.name,
    description: row.description,
    category: (row.category as NoteTemplateCategory) || "custom",
    icon: row.icon || "📄",
    origin: "custom",
    price: row.price_cents,
    content: row.content,
    creatorId: row.creator_id,
  };
}

interface NoteTemplatesState {
  customTemplates: NoteTemplate[];
  loading: boolean;
  initialized: boolean;
  refetch: () => Promise<void>;
}

export const useNoteTemplatesStore = create<NoteTemplatesState>((set) => ({
  customTemplates: [],
  loading: false,
  initialized: false,

  async refetch() {
    set({ loading: true });
    const { createClient } = await import("@/lib/supabase/client");
    const supabase = createClient();
    const { data } = await supabase
      .from("note_design_templates")
      .select("id, creator_id, name, description, category, icon, price_cents, content")
      .eq("is_published", true)
      .order("created_at", { ascending: false });
    set({
      customTemplates: ((data || []) as NoteTemplateRow[]).map(rowToTemplate),
      loading: false,
      initialized: true,
    });
  },
}));
