/**
 * ItemFormContext - 품목 폼 상태 컨텍스트
 *
 * 하위 컴포넌트에서 공유되는 폼 상태 관리
 */

'use client';

import { createContext, useContext, ReactNode } from 'react';
import type { UseFormReturn } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';
import type { ItemType } from '@/types/item';
import type { UseItemFormStateReturn } from '../hooks/useItemFormState';
import type { UseBOMManagementReturn } from '../hooks/useBOMManagement';
import type { UseBendingDetailsReturn } from '../hooks/useBendingDetails';

export interface ItemFormContextType {
  // React Hook Form
  form: UseFormReturn<CreateItemFormData>;

  // 모드
  mode: 'create' | 'edit';

  // 품목 유형
  selectedItemType: ItemType | '';
  setSelectedItemType: (type: ItemType | '') => void;

  // 부품 유형
  selectedPartType: string;
  setSelectedPartType: (type: string) => void;

  // 상태 훅
  formState: UseItemFormStateReturn;
  bomManagement: UseBOMManagementReturn;
  bendingDetails: UseBendingDetailsReturn;

  // 품목코드 생성
  generateItemCode: () => string;

  // 품목 유형 변경 핸들러
  handleItemTypeChange: (type: ItemType) => void;

  // 제출 상태
  isSubmitting: boolean;
}

const ItemFormContext = createContext<ItemFormContextType | null>(null);

export interface ItemFormProviderProps {
  children: ReactNode;
  value: ItemFormContextType;
}

export function ItemFormProvider({ children, value }: ItemFormProviderProps) {
  return (
    <ItemFormContext.Provider value={value}>
      {children}
    </ItemFormContext.Provider>
  );
}

export function useItemFormContext(): ItemFormContextType {
  const context = useContext(ItemFormContext);
  if (!context) {
    throw new Error('useItemFormContext must be used within an ItemFormProvider');
  }
  return context;
}

/**
 * 선택적으로 컨텍스트 사용 (컨텍스트가 없어도 에러 안 남)
 */
export function useOptionalItemFormContext(): ItemFormContextType | null {
  return useContext(ItemFormContext);
}

export default ItemFormContext;