/**
 * 품목 폼 상태 관리 커스텀 훅
 *
 * 25개 이상의 useState를 통합 관리
 */

import { useState, useCallback } from 'react';
import type { ItemMaster, ItemType, BendingDetail, BOMLine } from '@/types/item';
import type { UseFormSetValue, UseFormClearErrors } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';

export interface UseItemFormStateProps {
  mode: 'create' | 'edit';
  initialData?: Partial<ItemMaster>;
}

export interface ItemFormState {
  // 기본 상태
  isSubmitting: boolean;
  selectedItemType: ItemType | '';

  // 파일 상태
  specificationFile: File | null;
  certificationFile: File | null;
  bendingDiagramFile: File | null;
  bendingDiagram: string;
  bendingDiagramInputMethod: 'file' | 'drawing';
  isDrawingOpen: boolean;

  // FG(제품) 상태
  productName: string;
  productStatus: string;

  // PT(부품) 상태
  selectedPartType: string;
  partStatus: string;

  // SM/RM/CS 상태
  itemName: string;
  selectedCategory1: string;
  selectedInstallationType: string;
  materialStatus: string;
  selectedSpecification: string;
  selectedUnit: string;

  // ASSEMBLY 부품 상태
  sideSpecWidth: string;
  sideSpecHeight: string;
  assemblyLength: string;
  assemblyUnit: string;

  // 전동개폐기 상태
  electricOpenerPower: string;
  electricOpenerCapacity: string;

  // 모터/체인 상태
  motorVoltage: string;
  chainSpec: string;

  // BENDING 부품 상태
  selectedBendingItemType: string;
  material: string;
  bendingLength: string;
  widthSum: string;
  partUnit: string;
  bendingDetails: BendingDetail[];

  // BOM 상태
  bomLines: BOMLine[];
  bomSearchStates: Record<string, { searchValue: string; isOpen: boolean }>;
  needsBOM: boolean;

  // 비고
  remarks: string;
}

export function useItemFormState({ mode, initialData }: UseItemFormStateProps) {
  // 기본 상태
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedItemType, setSelectedItemType] = useState<ItemType | ''>(
    mode === 'edit' ? (initialData?.itemType || 'FG') : ''
  );

  // BOM 상태
  const [bomLines, setBomLines] = useState<BOMLine[]>(initialData?.bom || []);
  const [bomSearchStates, setBomSearchStates] = useState<Record<string, { searchValue: string; isOpen: boolean }>>({});

  // 파일 상태
  const [specificationFile, setSpecificationFile] = useState<File | null>(null);
  const [certificationFile, setCertificationFile] = useState<File | null>(null);
  const [bendingDiagramFile, setBendingDiagramFile] = useState<File | null>(null);
  const [bendingDiagram, setBendingDiagram] = useState<string>(initialData?.bendingDiagram || '');
  const [bendingDiagramInputMethod, setBendingDiagramInputMethod] = useState<'file' | 'drawing'>('file');
  const [isDrawingOpen, setIsDrawingOpen] = useState(false);

  // FG(제품) 상태
  const [productName, setProductName] = useState<string>(initialData?.itemName || '');
  const [productStatus, setProductStatus] = useState<string>(
    initialData?.isActive !== undefined ? String(initialData.isActive) : 'true'
  );

  // PT(부품) 상태
  const [selectedPartType, setSelectedPartType] = useState<string>(initialData?.partType || '');
  const [partStatus, setPartStatus] = useState<string>(
    initialData?.isActive !== undefined ? String(initialData.isActive) : 'true'
  );

  // SM/RM/CS 상태
  const [itemName, setItemName] = useState<string>(initialData?.itemName || '');
  const [selectedCategory1, setSelectedCategory1] = useState<string>(initialData?.category1 || '');
  const [selectedInstallationType, setSelectedInstallationType] = useState<string>(
    initialData?.installationType || ''
  );
  const [materialStatus, setMaterialStatus] = useState<string>(
    initialData?.isActive !== undefined ? String(initialData.isActive) : 'true'
  );
  const [selectedSpecification, setSelectedSpecification] = useState<string>(initialData?.specification || '');
  const [selectedUnit, setSelectedUnit] = useState<string>(initialData?.unit || '');

  // ASSEMBLY 부품 상태
  const [sideSpecWidth, setSideSpecWidth] = useState<string>(initialData?.sideSpecWidth || '');
  const [sideSpecHeight, setSideSpecHeight] = useState<string>(initialData?.sideSpecHeight || '');
  const [assemblyLength, setAssemblyLength] = useState<string>(initialData?.assemblyLength || '');
  const [assemblyUnit, setAssemblyUnit] = useState<string>(initialData?.unit || 'EA');

  // 전동개폐기 상태
  const [electricOpenerPower, setElectricOpenerPower] = useState<string>('');
  const [electricOpenerCapacity, setElectricOpenerCapacity] = useState<string>('');

  // 모터/체인 상태
  const [motorVoltage, setMotorVoltage] = useState<string>('');
  const [chainSpec, setChainSpec] = useState<string>('');

  // BENDING 부품 상태
  const [selectedBendingItemType, setSelectedBendingItemType] = useState<string>('');
  const [material, setMaterial] = useState<string>(initialData?.material || '');
  const [bendingLength, setBendingLength] = useState<string>(initialData?.bendingLength || '');
  const [widthSum, setWidthSum] = useState<string>(initialData?.length || '');
  const [partUnit, setPartUnit] = useState<string>(initialData?.unit || 'EA');
  const [bendingDetails, setBendingDetails] = useState<BendingDetail[]>(
    initialData?.bendingDetails || []
  );

  // BOM 필요 여부
  const [needsBOM, setNeedsBOM] = useState<boolean>(false);

  // 비고 (FG 전용)
  const [remarks, setRemarks] = useState<string>(initialData?.note || '');

  // 품목 유형 변경 시 모든 상태 초기화
  const resetAllStates = useCallback((
    setValue: UseFormSetValue<CreateItemFormData>,
    clearErrors: UseFormClearErrors<CreateItemFormData>,
    type: ItemType
  ) => {
    // FG(제품) 상태 초기화
    setProductName('');
    setProductStatus('true');

    // PT(부품) 상태 초기화
    setSelectedPartType('');
    setPartStatus('true');

    // SM/RM/CS 상태 초기화
    setItemName('');
    setSelectedCategory1('');
    setSelectedInstallationType('');
    setMaterialStatus('true');
    setSelectedSpecification('');
    setSelectedUnit('');

    // ASSEMBLY 부품 상태 초기화
    setSideSpecWidth('');
    setSideSpecHeight('');
    setAssemblyLength('');
    setAssemblyUnit('EA');

    // 전동개폐기 상태 초기화
    setElectricOpenerPower('');
    setElectricOpenerCapacity('');

    // 모터/체인 상태 초기화
    setMotorVoltage('');
    setChainSpec('');

    // BENDING 부품 상태 초기화
    setSelectedBendingItemType('');
    setMaterial('');
    setBendingLength('');
    setWidthSum('');
    setPartUnit('EA');
    setBendingDetails([]);

    // BOM 및 파일 초기화
    setNeedsBOM(false);
    setBomLines([]);
    setSpecificationFile(null);
    setCertificationFile(null);
    setBendingDiagramFile(null);
    setBendingDiagram('');

    // react-hook-form 필드 초기화
    setValue('itemCode', '');
    setValue('itemName', '');
    setValue('unit', (type === 'SM' || type === 'RM' || type === 'CS') ? '' : 'EA');
    setValue('specification', '');
    setValue('purchasePrice', 0);
    setValue('salesPrice', 0);
    setValue('processingCost', 0);
    setValue('laborCost', 0);
    setValue('installCost', 0);
    setValue('isActive', true);

    // 검증 에러 초기화
    clearErrors();
  }, []);

  // 부품 유형 변경 시 부품 관련 상태만 초기화
  const resetPartStates = useCallback((
    setValue: UseFormSetValue<CreateItemFormData>
  ) => {
    // 공통 필드 초기화
    setSelectedCategory1('');
    setValue('category1', undefined);
    setPartUnit('EA');
    setValue('unit', 'EA');

    // ASSEMBLY 부품 전용 필드 초기화
    setSelectedInstallationType('');
    setValue('installationType', undefined);
    setSideSpecWidth('');
    setValue('sideSpecWidth', '');
    setSideSpecHeight('');
    setValue('sideSpecHeight', '');
    setAssemblyLength('');
    setValue('assemblyLength', '');
    setAssemblyUnit('EA');

    // BENDING 부품 전용 필드 초기화
    setSelectedBendingItemType('');
    setValue('category2', undefined);
    setMaterial('');
    setValue('material', '');
    setWidthSum('');
    setValue('length', '');
    setBendingLength('');
    setValue('bendingLength', '');
    setBendingDetails([]);

    // PURCHASED 부품 전용 필드 초기화
    setElectricOpenerPower('');
    setValue('electricOpenerPower', '');
    setElectricOpenerCapacity('');
    setValue('electricOpenerCapacity', '');
    setMotorVoltage('');
    setValue('motorVoltage', '');
    setChainSpec('');
    setValue('chainSpec', '');
  }, []);

  return {
    // 기본 상태
    isSubmitting,
    setIsSubmitting,
    selectedItemType,
    setSelectedItemType,

    // BOM 상태
    bomLines,
    setBomLines,
    bomSearchStates,
    setBomSearchStates,

    // 파일 상태
    specificationFile,
    setSpecificationFile,
    certificationFile,
    setCertificationFile,
    bendingDiagramFile,
    setBendingDiagramFile,
    bendingDiagram,
    setBendingDiagram,
    bendingDiagramInputMethod,
    setBendingDiagramInputMethod,
    isDrawingOpen,
    setIsDrawingOpen,

    // FG(제품) 상태
    productName,
    setProductName,
    productStatus,
    setProductStatus,

    // PT(부품) 상태
    selectedPartType,
    setSelectedPartType,
    partStatus,
    setPartStatus,

    // SM/RM/CS 상태
    itemName,
    setItemName,
    selectedCategory1,
    setSelectedCategory1,
    selectedInstallationType,
    setSelectedInstallationType,
    materialStatus,
    setMaterialStatus,
    selectedSpecification,
    setSelectedSpecification,
    selectedUnit,
    setSelectedUnit,

    // ASSEMBLY 부품 상태
    sideSpecWidth,
    setSideSpecWidth,
    sideSpecHeight,
    setSideSpecHeight,
    assemblyLength,
    setAssemblyLength,
    assemblyUnit,
    setAssemblyUnit,

    // 전동개폐기 상태
    electricOpenerPower,
    setElectricOpenerPower,
    electricOpenerCapacity,
    setElectricOpenerCapacity,

    // 모터/체인 상태
    motorVoltage,
    setMotorVoltage,
    chainSpec,
    setChainSpec,

    // BENDING 부품 상태
    selectedBendingItemType,
    setSelectedBendingItemType,
    material,
    setMaterial,
    bendingLength,
    setBendingLength,
    widthSum,
    setWidthSum,
    partUnit,
    setPartUnit,
    bendingDetails,
    setBendingDetails,

    // BOM 필요 여부
    needsBOM,
    setNeedsBOM,

    // 비고
    remarks,
    setRemarks,

    // 헬퍼 함수
    resetAllStates,
    resetPartStates,
  };
}

export type UseItemFormStateReturn = ReturnType<typeof useItemFormState>;