'use client';

import { useCallback } from 'react';
import { useItemMaster } from '@/contexts/ItemMasterContext';
import { toast } from 'sonner';
import type { ItemPage, BOMItem } from '@/contexts/ItemMasterContext';
import type { CustomTab, AttributeSubTab } from './useTabManagement';
import type { MasterOption, OptionColumn } from '../types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// 타입 alias (기존 호환성)
type UnitOption = MasterOption;
type MaterialOption = MasterOption;
type SurfaceTreatmentOption = MasterOption;

export interface UseDeleteManagementReturn {
  handleDeletePage: (pageId: number) => void;
  handleDeleteSection: (pageId: number, sectionId: number) => void;
  handleUnlinkField: (pageId: string, sectionId: string, fieldId: string) => Promise<void>;
  handleResetAllData: (
    setUnitOptions: React.Dispatch<React.SetStateAction<UnitOption[]>>,
    setMaterialOptions: React.Dispatch<React.SetStateAction<MaterialOption[]>>,
    setSurfaceTreatmentOptions: React.Dispatch<React.SetStateAction<SurfaceTreatmentOption[]>>,
    setCustomAttributeOptions: React.Dispatch<React.SetStateAction<Record<string, UnitOption[]>>>,
    setAttributeColumns: React.Dispatch<React.SetStateAction<Record<string, OptionColumn[]>>>,
    setBomItems: React.Dispatch<React.SetStateAction<BOMItem[]>>,
    setCustomTabs: React.Dispatch<React.SetStateAction<CustomTab[]>>,
    setAttributeSubTabs: React.Dispatch<React.SetStateAction<AttributeSubTab[]>>,
  ) => void;
}

interface UseDeleteManagementProps {
  itemPages: ItemPage[];
}

export function useDeleteManagement({ itemPages }: UseDeleteManagementProps): UseDeleteManagementReturn {
  const {
    deleteItemPage,
    deleteSection,
    unlinkFieldFromSection,
    resetAllData,
  } = useItemMaster();

  // 페이지 삭제 핸들러
  const handleDeletePage = useCallback((pageId: number) => {
    const pageToDelete = itemPages.find(p => p.id === pageId);
    const _sectionIds = pageToDelete?.sections.map(s => s.id) || [];
    const _fieldIds = pageToDelete?.sections.flatMap(s => s.fields?.map(f => f.id) || []) || [];
    deleteItemPage(pageId);
  }, [itemPages, deleteItemPage]);

  // 섹션 삭제 핸들러
  const handleDeleteSection = useCallback((pageId: number, sectionId: number) => {
    const page = itemPages.find(p => p.id === pageId);
    const sectionToDelete = page?.sections.find(s => s.id === sectionId);
    const _fieldIds = sectionToDelete?.fields?.map(f => f.id) || [];
    deleteSection(Number(sectionId));
  }, [itemPages, deleteSection]);

  // 필드 연결 해제 핸들러
  const handleUnlinkField = useCallback(async (_pageId: string, sectionId: string, fieldId: string) => {
    try {
      await unlinkFieldFromSection(Number(sectionId), Number(fieldId));
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('필드 연결 해제 실패:', error);
      toast.error('필드 연결 해제에 실패했습니다');
    }
  }, [unlinkFieldFromSection]);

  // 전체 데이터 초기화 핸들러
  const handleResetAllData = useCallback((
    setUnitOptions: React.Dispatch<React.SetStateAction<UnitOption[]>>,
    setMaterialOptions: React.Dispatch<React.SetStateAction<MaterialOption[]>>,
    setSurfaceTreatmentOptions: React.Dispatch<React.SetStateAction<SurfaceTreatmentOption[]>>,
    setCustomAttributeOptions: React.Dispatch<React.SetStateAction<Record<string, UnitOption[]>>>,
    setAttributeColumns: React.Dispatch<React.SetStateAction<Record<string, OptionColumn[]>>>,
    setBomItems: React.Dispatch<React.SetStateAction<BOMItem[]>>,
    setCustomTabs: React.Dispatch<React.SetStateAction<CustomTab[]>>,
    setAttributeSubTabs: React.Dispatch<React.SetStateAction<AttributeSubTab[]>>,
  ) => {
    if (!confirm('⚠️ 경고: 모든 품목기준관리 데이터(계층구조, 섹션, 항목, 속성)를 초기화하시겠습니까?\n\n이 작업은 되돌릴 수 없습니다!')) {
      return;
    }

    try {
      resetAllData();

      setUnitOptions([]);
      setMaterialOptions([]);
      setSurfaceTreatmentOptions([]);
      setCustomAttributeOptions({});
      setAttributeColumns({});
      setBomItems([]);

      setCustomTabs([
        { id: 'hierarchy', label: '계층구조', icon: 'FolderTree', isDefault: true, order: 1 },
        { id: 'sections', label: '섹션', icon: 'Layers', isDefault: true, order: 2 },
        { id: 'items', label: '항목', icon: 'ListTree', isDefault: true, order: 3 },
        { id: 'attributes', label: '속성', icon: 'Settings', isDefault: true, order: 4 }
      ]);

      setAttributeSubTabs([]);

      toast.success('✅ 모든 데이터가 초기화되었습니다!\n계층구조, 섹션, 항목, 속성이 모두 삭제되었습니다.');

      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('초기화 중 오류가 발생했습니다');
      console.error('Reset error:', error);
    }
  }, [resetAllData]);

  return {
    handleDeletePage,
    handleDeleteSection,
    handleUnlinkField,
    handleResetAllData,
  };
}
