'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
import { toast } from 'sonner';
import type { ChecklistCategory } from '../types';
import { getChecklistTemplate, saveChecklistTemplate } from '../actions';

function generateId() {
  return `item-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
}

export function useChecklistTemplate() {
  const [templateId, setTemplateId] = useState<number | null>(null);
  const [editCategories, setEditCategories] = useState<ChecklistCategory[]>([]);
  const savedRef = useRef<ChecklistCategory[]>([]);

  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [hasChanges, setHasChanges] = useState(false);

  // === 초기 로드 ===
  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);

    getChecklistTemplate('day1_audit')
      .then((result) => {
        if (cancelled) return;
        if (result.success && result.data) {
          setTemplateId(result.data.id);
          const cats = result.data.categories;
          setEditCategories(structuredClone(cats));
          savedRef.current = structuredClone(cats);
        } else {
          setError(result.error || '템플릿 로드 실패');
        }
      })
      .catch(() => {
        if (!cancelled) setError('템플릿 로드 중 오류 발생');
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => { cancelled = true; };
  }, []);

  // === 변경 추적 ===
  const markChanged = useCallback(() => setHasChanges(true), []);

  // === 카테고리 CRUD ===
  const addCategory = useCallback(() => {
    setEditCategories(prev => [
      ...prev,
      { id: generateId(), title: '새 카테고리', subItems: [] },
    ]);
    markChanged();
  }, [markChanged]);

  const updateCategoryTitle = useCallback((categoryId: string, title: string) => {
    setEditCategories(prev =>
      prev.map(cat => cat.id === categoryId ? { ...cat, title } : cat)
    );
    markChanged();
  }, [markChanged]);

  const deleteCategory = useCallback((categoryId: string) => {
    setEditCategories(prev => prev.filter(cat => cat.id !== categoryId));
    markChanged();
  }, [markChanged]);

  // === 카테고리 순서 변경 ===
  const moveCategoryUp = useCallback((index: number) => {
    if (index <= 0) return;
    setEditCategories(prev => {
      const next = [...prev];
      [next[index - 1], next[index]] = [next[index], next[index - 1]];
      return next;
    });
    markChanged();
  }, [markChanged]);

  const moveCategoryDown = useCallback((index: number) => {
    setEditCategories(prev => {
      if (index >= prev.length - 1) return prev;
      const next = [...prev];
      [next[index], next[index + 1]] = [next[index + 1], next[index]];
      return next;
    });
    markChanged();
  }, [markChanged]);

  // === 하위 항목 CRUD ===
  const addSubItem = useCallback((categoryId: string) => {
    setEditCategories(prev =>
      prev.map(cat => {
        if (cat.id !== categoryId) return cat;
        return {
          ...cat,
          subItems: [
            ...cat.subItems,
            { id: generateId(), name: '새 항목', isCompleted: false },
          ],
        };
      })
    );
    markChanged();
  }, [markChanged]);

  const updateSubItemName = useCallback((categoryId: string, subItemId: string, name: string) => {
    setEditCategories(prev =>
      prev.map(cat => {
        if (cat.id !== categoryId) return cat;
        return {
          ...cat,
          subItems: cat.subItems.map(item =>
            item.id === subItemId ? { ...item, name } : item
          ),
        };
      })
    );
    markChanged();
  }, [markChanged]);

  const deleteSubItem = useCallback((categoryId: string, subItemId: string) => {
    setEditCategories(prev =>
      prev.map(cat => {
        if (cat.id !== categoryId) return cat;
        return {
          ...cat,
          subItems: cat.subItems.filter(item => item.id !== subItemId),
        };
      })
    );
    markChanged();
  }, [markChanged]);

  // === 하위 항목 순서 변경 ===
  const moveSubItemUp = useCallback((categoryId: string, index: number) => {
    if (index <= 0) return;
    setEditCategories(prev =>
      prev.map(cat => {
        if (cat.id !== categoryId) return cat;
        const items = [...cat.subItems];
        [items[index - 1], items[index]] = [items[index], items[index - 1]];
        return { ...cat, subItems: items };
      })
    );
    markChanged();
  }, [markChanged]);

  const moveSubItemDown = useCallback((categoryId: string, index: number) => {
    setEditCategories(prev =>
      prev.map(cat => {
        if (cat.id !== categoryId) return cat;
        if (index >= cat.subItems.length - 1) return cat;
        const items = [...cat.subItems];
        [items[index], items[index + 1]] = [items[index + 1], items[index]];
        return { ...cat, subItems: items };
      })
    );
    markChanged();
  }, [markChanged]);

  // === 저장 ===
  const saveTemplate = useCallback(async () => {
    if (!templateId) return;

    setSaving(true);
    try {
      // API용 데이터: isCompleted 제거
      const apiCategories = editCategories.map(cat => ({
        id: cat.id,
        title: cat.title,
        subItems: cat.subItems.map(item => ({
          id: item.id,
          name: item.name,
        })),
      }));

      const result = await saveChecklistTemplate(templateId, {
        categories: apiCategories,
      });

      if (result.success && result.data) {
        const cats = result.data.categories;
        setEditCategories(structuredClone(cats));
        savedRef.current = structuredClone(cats);
        setHasChanges(false);
        toast.success('점검표가 저장되었습니다.');
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setSaving(false);
    }
  }, [editCategories, templateId]);

  // === 초기화 ===
  const resetToSaved = useCallback(() => {
    setEditCategories(structuredClone(savedRef.current));
    setHasChanges(false);
  }, []);

  return {
    // 데이터
    templateId,
    editCategories,
    hasChanges,
    saving,
    loading,
    error,

    // 카테고리
    addCategory,
    updateCategoryTitle,
    deleteCategory,
    moveCategoryUp,
    moveCategoryDown,

    // 하위 항목
    addSubItem,
    updateSubItemName,
    deleteSubItem,
    moveSubItemUp,
    moveSubItemDown,

    // 저장/초기화
    saveTemplate,
    resetToSaved,
  };
}
