"use client";

import { useState, useCallback, useMemo, useEffect } from "react";
import { useStorage } from "@/core/storage";
import { v4 as uuid } from "uuid";
import type { PromptTemplate, PromptHistoryEntry, OutputMode } from "../types";
import { BUILTIN_TEMPLATES } from "../services/builtin-templates";
import { composePrompt } from "../services/prompt-composer";

const HISTORY_PREFIX = "history:";
const TEMPLATE_PREFIX = "template:";

export function usePromptGenerator() {
  const storage = useStorage("prompt-generator");
  const [selectedTemplate, setSelectedTemplate] =
    useState<PromptTemplate | null>(null);
  const [values, setValues] = useState<Record<string, unknown>>({});
  const [customTemplates, setCustomTemplates] = useState<PromptTemplate[]>([]);
  const [history, setHistory] = useState<PromptHistoryEntry[]>([]);
  const [loading, setLoading] = useState(true);

  const allTemplates = useMemo(
    () => [...BUILTIN_TEMPLATES, ...customTemplates],
    [customTemplates],
  );

  // Load custom templates and history
  useEffect(() => {
    async function load() {
      setLoading(true);
      const all = await storage.exportAll();
      const templates: PromptTemplate[] = [];
      const entries: PromptHistoryEntry[] = [];
      for (const [key, value] of Object.entries(all)) {
        if (!value) continue;
        if (key.startsWith(TEMPLATE_PREFIX)) {
          templates.push(value as PromptTemplate);
        } else if (key.startsWith(HISTORY_PREFIX)) {
          entries.push(value as PromptHistoryEntry);
        }
      }
      entries.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
      setCustomTemplates(templates);
      setHistory(entries);
      setLoading(false);
    }
    load();
  }, [storage]);

  const selectTemplate = useCallback((template: PromptTemplate) => {
    setSelectedTemplate(template);
    // Initialize values with defaults
    const defaults: Record<string, unknown> = {};
    for (const v of template.variables) {
      if (v.defaultValue !== undefined) defaults[v.id] = v.defaultValue;
    }
    setValues(defaults);
  }, []);

  const updateValue = useCallback((variableId: string, value: unknown) => {
    setValues((prev) => ({ ...prev, [variableId]: value }));
  }, []);

  const composedPrompt = useMemo(() => {
    if (!selectedTemplate) return "";
    return composePrompt(selectedTemplate, values);
  }, [selectedTemplate, values]);

  const saveToHistory = useCallback(async () => {
    if (!selectedTemplate || !composedPrompt) return;
    const entry: PromptHistoryEntry = {
      id: uuid(),
      templateId: selectedTemplate.id,
      templateName: selectedTemplate.name,
      templateVersion: selectedTemplate.version,
      values: { ...values },
      composedPrompt,
      outputMode: selectedTemplate.outputMode,
      providerProfile: selectedTemplate.providerProfile ?? null,
      safetyBlocks:
        selectedTemplate.safetyBlocks
          ?.filter((s) => s.enabled)
          .map((s) => s.id) ?? [],
      tags: selectedTemplate.tags,
      isFavorite: false,
      createdAt: new Date().toISOString(),
    };
    await storage.set(`${HISTORY_PREFIX}${entry.id}`, entry);
    setHistory((prev) => [entry, ...prev]);
    return entry;
  }, [storage, selectedTemplate, values, composedPrompt]);

  const deleteHistoryEntry = useCallback(
    async (id: string) => {
      await storage.delete(`${HISTORY_PREFIX}${id}`);
      setHistory((prev) => prev.filter((h) => h.id !== id));
    },
    [storage],
  );

  const clearSelection = useCallback(() => {
    setSelectedTemplate(null);
    setValues({});
  }, []);

  return {
    allTemplates,
    selectedTemplate,
    values,
    composedPrompt,
    history,
    loading,
    selectTemplate,
    updateValue,
    saveToHistory,
    deleteHistoryEntry,
    clearSelection,
  };
}
