'use client';

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

export function useDay1Audit() {
  // 데이터 상태
  const [templateId, setTemplateId] = useState<number | null>(null);
  const [categories, setCategories] = useState<ChecklistCategory[]>([]);

  // 선택 상태
  const [selectedSubItemId, setSelectedSubItemId] = useState<string | null>(null);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);

  // 로딩 상태
  const [loadingChecklist, setLoadingChecklist] = useState(true);
  const [pendingToggleIds, setPendingToggleIds] = useState<Set<string>>(new Set());

  // 마운트 시 점검표 로드 (checklist_templates API)
  useEffect(() => {
    let cancelled = false;
    setLoadingChecklist(true);

    getChecklistTemplate('day1_audit')
      .then((result) => {
        if (cancelled) return;
        if (result.success && result.data) {
          setTemplateId(result.data.id);
          setCategories(result.data.categories);
        }
      })
      .finally(() => {
        if (!cancelled) setLoadingChecklist(false);
      });

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

  // 진행률 계산
  const day1Progress = useMemo(() => {
    const total = categories.reduce((sum, cat) => sum + cat.subItems.length, 0);
    const completed = categories.reduce(
      (sum, cat) => sum + cat.subItems.filter((item) => item.isCompleted).length,
      0,
    );
    return { completed, total };
  }, [categories]);

  // 선택된 항목의 완료 여부
  const isSelectedItemCompleted = useMemo(() => {
    if (!selectedSubItemId) return false;
    for (const cat of categories) {
      const item = cat.subItems.find((sub) => sub.id === selectedSubItemId);
      if (item) return item.isCompleted;
    }
    return false;
  }, [categories, selectedSubItemId]);

  // 선택된 점검 항목 정보 (중앙 패널용)
  const selectedCheckItem = useMemo(() => {
    if (!selectedSubItemId || !selectedCategoryId) return null;
    const category = categories.find((c) => c.id === selectedCategoryId);
    if (!category) return null;
    const subItem = category.subItems.find((s) => s.id === selectedSubItemId);
    if (!subItem) return null;

    return {
      id: `check-${subItem.id}`,
      categoryId: category.id,
      subItemId: subItem.id,
      title: subItem.name,
      description: '',
      buttonLabel: '기준/매뉴얼 확인',
      standardDocuments: [],
    };
  }, [selectedSubItemId, selectedCategoryId, categories]);

  // === 핸들러 ===

  const handleSubItemSelect = useCallback((categoryId: string, subItemId: string) => {
    setSelectedCategoryId(categoryId);
    setSelectedSubItemId(subItemId);
  }, []);

  const handleSubItemToggle = useCallback(async (categoryId: string, subItemId: string) => {
    if (!templateId || pendingToggleIds.has(subItemId)) return;
    setPendingToggleIds((prev) => new Set(prev).add(subItemId));

    try {
      const result = await toggleTemplateItem(templateId, subItemId);
      if (result.success && result.data) {
        setCategories((prev) =>
          prev.map((cat) => {
            if (cat.id !== categoryId) return cat;
            return {
              ...cat,
              subItems: cat.subItems.map((item) => {
                if (item.id !== subItemId) return item;
                return { ...item, isCompleted: result.data!.isCompleted };
              }),
            };
          }),
        );
      } else {
        toast.error(result.error || '항목 상태 변경에 실패했습니다.');
      }
    } finally {
      setPendingToggleIds((prev) => {
        const next = new Set(prev);
        next.delete(subItemId);
        return next;
      });
    }
  }, [templateId, pendingToggleIds]);

  const handleConfirmComplete = useCallback(() => {
    if (selectedCategoryId && selectedSubItemId) {
      handleSubItemToggle(selectedCategoryId, selectedSubItemId);
    }
  }, [selectedCategoryId, selectedSubItemId, handleSubItemToggle]);

  return {
    // 데이터
    templateId,
    categories,
    day1Progress,
    selectedCheckItem,
    isSelectedItemCompleted,

    // 선택
    selectedSubItemId,
    handleSubItemSelect,

    // 토글
    handleSubItemToggle,
    handleConfirmComplete,
    pendingToggleIds,

    // 로딩
    loadingChecklist,

    // Mock 여부
    isMock: false,
  };
}
