import { useState, useEffect, useCallback, useMemo } from 'react';
import { StyleOption } from '../types';
import { loadTemplates, ensureTemplatesFolder, openTemplatesFolder } from '../services/templateLoader';

interface UseTemplatesReturn {
  templates: StyleOption[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  openFolder: () => Promise<void>;
  getTemplate: (id: string) => StyleOption | undefined;
  categories: string[];
  templatesByCategory: Map<string, StyleOption[]>;
}

export const useTemplates = (): UseTemplatesReturn => {
  const [templates, setTemplates] = useState<StyleOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const result = await loadTemplates();
      setTemplates(result.templates);
      if (result.error) {
        setError(result.error);
      } else if (result.templates.length === 0) {
        setError('No templates found. Click "Open Templates Folder" to see where they should be.');
      }
    } catch (e) {
      console.error('Failed to load templates:', e);
      const errorMsg = e instanceof Error ? e.message : String(e);
      setError(`Failed to load templates: ${errorMsg}`);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const openFolder = useCallback(async () => {
    try {
      const result = await openTemplatesFolder();
      if (!result.success && result.error) {
        setError(`Failed to open folder: ${result.error}`);
      }
    } catch (e) {
      console.error('Failed to open templates folder:', e);
      setError('Failed to open templates folder. Try navigating to the folder manually.');
    }
  }, []);

  useEffect(() => {
    refresh();
  }, [refresh]);

  const getTemplate = useCallback((id: string) => {
    return templates.find(t => t.id === id);
  }, [templates]);

  const categories = useMemo(() => {
    const cats = new Set<string>();
    templates.forEach(t => cats.add(t.category));
    return Array.from(cats).sort();
  }, [templates]);

  const templatesByCategory = useMemo(() => {
    const map = new Map<string, StyleOption[]>();
    templates.forEach(t => {
      if (!map.has(t.category)) {
        map.set(t.category, []);
      }
      map.get(t.category)!.push(t);
    });
    return map;
  }, [templates]);

  return {
    templates,
    isLoading,
    error,
    refresh,
    openFolder,
    getTemplate,
    categories,
    templatesByCategory,
  };
};
