'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { useItemMaster } from '@/contexts/ItemMasterContext';
import { useErrorAlert } from '../contexts';
import type { ItemMasterField } from '@/contexts/ItemMasterContext';
import { masterFieldService } from '../services';
import { ApiError } from '@/lib/api/error-handler';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// 필드 타입 정의 - field_type 캐스팅용
type FieldTypeValue = 'textbox' | 'number' | 'dropdown' | 'checkbox' | 'date' | 'textarea';

/**
 * @deprecated 2025-11-27: item_fields로 통합됨.
 * - itemMasterFields → item_fields WHERE section_id IS NULL
 * - 내부적으로 fields.* API를 사용하도록 마이그레이션 완료
 * - 향후 독립 필드 관리용 훅으로 리네임 예정
 */
export interface UseMasterFieldManagementReturn {
  // 다이얼로그 상태
  isMasterFieldDialogOpen: boolean;
  setIsMasterFieldDialogOpen: (open: boolean) => void;
  editingMasterFieldId: number | null;
  setEditingMasterFieldId: (id: number | null) => void;

  // 폼 상태
  newMasterFieldName: string;
  setNewMasterFieldName: (name: string) => void;
  newMasterFieldKey: string;
  setNewMasterFieldKey: (key: string) => void;
  // string 타입으로 유연하게 처리
  newMasterFieldInputType: string;
  setNewMasterFieldInputType: (type: string) => void;
  newMasterFieldRequired: boolean;
  setNewMasterFieldRequired: (required: boolean) => void;
  newMasterFieldCategory: string;
  setNewMasterFieldCategory: (category: string) => void;
  newMasterFieldDescription: string;
  setNewMasterFieldDescription: (desc: string) => void;
  newMasterFieldOptions: string;
  setNewMasterFieldOptions: (options: string) => void;
  // string 타입으로 유연하게 처리
  newMasterFieldAttributeType: string;
  setNewMasterFieldAttributeType: (type: string) => void;
  newMasterFieldMultiColumn: boolean;
  setNewMasterFieldMultiColumn: (multi: boolean) => void;
  newMasterFieldColumnCount: number;
  setNewMasterFieldColumnCount: (count: number) => void;
  newMasterFieldColumnNames: string[];
  setNewMasterFieldColumnNames: React.Dispatch<React.SetStateAction<string[]>>;

  // 핸들러
  handleAddMasterField: () => Promise<void>;
  handleEditMasterField: (field: ItemMasterField) => void;
  handleUpdateMasterField: () => Promise<void>;
  handleDeleteMasterField: (id: number) => Promise<void>;
  resetMasterFieldForm: () => void;
}

export function useMasterFieldManagement(): UseMasterFieldManagementReturn {
  const {
    itemMasterFields: _itemMasterFields,
    addItemMasterField,
    updateItemMasterField,
    deleteItemMasterField,
  } = useItemMaster();

  // 에러 알림 (AlertDialog로 표시)
  const { showErrorAlert } = useErrorAlert();

  // 다이얼로그 상태
  const [isMasterFieldDialogOpen, setIsMasterFieldDialogOpen] = useState(false);
  const [editingMasterFieldId, setEditingMasterFieldId] = useState<number | null>(null);

  // 폼 상태
  const [newMasterFieldName, setNewMasterFieldName] = useState('');
  const [newMasterFieldKey, setNewMasterFieldKey] = useState('');
  const [newMasterFieldInputType, setNewMasterFieldInputType] = useState<string>('textbox');
  const [newMasterFieldRequired, setNewMasterFieldRequired] = useState(false);
  const [newMasterFieldCategory, setNewMasterFieldCategory] = useState('공통');
  const [newMasterFieldDescription, setNewMasterFieldDescription] = useState('');
  const [newMasterFieldOptions, setNewMasterFieldOptions] = useState('');
  const [newMasterFieldAttributeType, setNewMasterFieldAttributeType] = useState<string>('custom');
  const [newMasterFieldMultiColumn, setNewMasterFieldMultiColumn] = useState(false);
  const [newMasterFieldColumnCount, setNewMasterFieldColumnCount] = useState(2);
  const [newMasterFieldColumnNames, setNewMasterFieldColumnNames] = useState<string[]>(['컬럼1', '컬럼2']);

  // 마스터 항목 추가
  const handleAddMasterField = async () => {
    if (!newMasterFieldName.trim() || !newMasterFieldKey.trim()) {
      toast.error('항목명과 필드 키를 입력해주세요');
      return;
    }

    // ItemMasterField 타입에 맞게 필수 필드 포함
    // 2025-11-28: field_key 추가 (백엔드에서 {ID}_{입력값} 형태로 저장)
    const newMasterFieldData: Omit<ItemMasterField, 'id' | 'tenant_id' | 'created_by' | 'updated_by' | 'created_at' | 'updated_at'> = {
      field_name: newMasterFieldName,
      field_key: newMasterFieldKey, // 2025-11-28: field_key 추가
      field_type: newMasterFieldInputType as FieldTypeValue,
      category: newMasterFieldCategory || null,
      description: newMasterFieldDescription || null,
      is_common: false,
      default_value: null,
      options: newMasterFieldInputType === 'dropdown' && newMasterFieldOptions.trim()
        ? newMasterFieldOptions.split(',').map(o => ({ label: o.trim(), value: o.trim() }))
        : null,
      validation_rules: null,
      properties: {
        required: newMasterFieldRequired,
        attributeType: newMasterFieldInputType === 'dropdown' ? newMasterFieldAttributeType : undefined,
        multiColumn: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') ? newMasterFieldMultiColumn : undefined,
        columnCount: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') && newMasterFieldMultiColumn ? newMasterFieldColumnCount : undefined,
        columnNames: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') && newMasterFieldMultiColumn ? newMasterFieldColumnNames : undefined
      },
    };

    try {
      await addItemMasterField(newMasterFieldData as any);
      resetMasterFieldForm();
      toast.success('항목이 추가되었습니다');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('항목 추가 실패:', error);

      // 422 ValidationException 상세 메시지 처리 (field_key 중복/예약어) → AlertDialog로 표시
      if (error instanceof ApiError) {
        // errors 객체에서 첫 번째 에러 메시지 추출
        if (error.errors && Object.keys(error.errors).length > 0) {
          const firstKey = Object.keys(error.errors)[0];
          const firstError = error.errors[firstKey];
          const errorMessage = Array.isArray(firstError) ? firstError[0] : firstError;
          showErrorAlert(errorMessage, '항목 추가 실패');
        } else {
          showErrorAlert(error.message, '항목 추가 실패');
        }
      } else {
        showErrorAlert('항목 추가에 실패했습니다', '오류');
      }
    }
  };

  // 마스터 항목 수정 시작
  // 2025-12-01: masterFieldService.toFormData() 사용으로 리팩토링
  const handleEditMasterField = (field: ItemMasterField) => {
    setEditingMasterFieldId(field.id);

    // masterFieldService를 사용하여 폼 데이터 변환
    const formData = masterFieldService.toFormData(field);
    setNewMasterFieldName(formData.name);
    setNewMasterFieldKey(formData.key);
    setNewMasterFieldInputType(formData.inputType);
    setNewMasterFieldRequired(formData.required);
    setNewMasterFieldCategory(formData.category);
    setNewMasterFieldDescription(formData.description);
    setNewMasterFieldOptions(formData.options);
    setNewMasterFieldAttributeType(formData.attributeType);
    setNewMasterFieldMultiColumn(formData.multiColumn);
    setNewMasterFieldColumnCount(formData.columnCount);
    setNewMasterFieldColumnNames(formData.columnNames);

    setIsMasterFieldDialogOpen(true);
  };

  // 마스터 항목 업데이트
  const handleUpdateMasterField = async () => {
    if (!editingMasterFieldId || !newMasterFieldName.trim() || !newMasterFieldKey.trim()) {
      toast.error('항목명과 필드 키를 입력해주세요');
      return;
    }

    // 2025-11-28: field_key 수정 시에도 API 요청에 포함
    const updateData: Partial<ItemMasterField> = {
      field_name: newMasterFieldName,
      field_key: newMasterFieldKey, // 2025-11-28: field_key 추가
      field_type: newMasterFieldInputType as FieldTypeValue,
      category: newMasterFieldCategory || null,
      description: newMasterFieldDescription || null,
      options: newMasterFieldInputType === 'dropdown' && newMasterFieldOptions.trim()
        ? newMasterFieldOptions.split(',').map(o => ({ label: o.trim(), value: o.trim() }))
        : null,
      properties: {
        required: newMasterFieldRequired,
        attributeType: newMasterFieldInputType === 'dropdown' ? newMasterFieldAttributeType : undefined,
        multiColumn: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') ? newMasterFieldMultiColumn : undefined,
        columnCount: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') && newMasterFieldMultiColumn ? newMasterFieldColumnCount : undefined,
        columnNames: (newMasterFieldInputType === 'textbox' || newMasterFieldInputType === 'textarea') && newMasterFieldMultiColumn ? newMasterFieldColumnNames : undefined
      },
    };

    try {
      await updateItemMasterField(editingMasterFieldId, updateData);
      resetMasterFieldForm();
      toast.success('항목이 수정되었습니다');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('항목 수정 실패:', error);

      // 422 ValidationException 상세 메시지 처리 (field_key 중복/예약어, field_name 중복 등) → AlertDialog로 표시
      if (error instanceof ApiError) {
        // errors 객체에서 첫 번째 에러 메시지 추출
        if (error.errors && Object.keys(error.errors).length > 0) {
          const firstKey = Object.keys(error.errors)[0];
          const firstError = error.errors[firstKey];
          const errorMessage = Array.isArray(firstError) ? firstError[0] : firstError;
          showErrorAlert(errorMessage, '항목 수정 실패');
        } else {
          showErrorAlert(error.message, '항목 수정 실패');
        }
      } else {
        showErrorAlert('항목 수정에 실패했습니다', '오류');
      }
    }
  };

  // 항목 삭제 (2025-11-27: 마스터 항목 → 항목으로 통합)
  const handleDeleteMasterField = async (id: number) => {
    if (confirm('이 항목을 삭제하시겠습니까?\n(섹션에서 사용 중인 경우 연결도 함께 해제됩니다)')) {
      try {
        await deleteItemMasterField(id);
        toast.success('항목이 삭제되었습니다');
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('항목 삭제 실패:', error);

        if (error instanceof ApiError) {
          toast.error(error.message);
        } else {
          toast.error('항목 삭제에 실패했습니다');
        }
      }
    }
  };

  // 폼 초기화
  const resetMasterFieldForm = () => {
    setEditingMasterFieldId(null);
    setNewMasterFieldName('');
    setNewMasterFieldKey('');
    setNewMasterFieldInputType('textbox');
    setNewMasterFieldRequired(false);
    setNewMasterFieldCategory('공통');
    setNewMasterFieldDescription('');
    setNewMasterFieldOptions('');
    setNewMasterFieldAttributeType('custom');
    setNewMasterFieldMultiColumn(false);
    setNewMasterFieldColumnCount(2);
    setNewMasterFieldColumnNames(['컬럼1', '컬럼2']);
    setIsMasterFieldDialogOpen(false);
  };

  return {
    // 다이얼로그 상태
    isMasterFieldDialogOpen,
    setIsMasterFieldDialogOpen,
    editingMasterFieldId,
    setEditingMasterFieldId,

    // 폼 상태
    newMasterFieldName,
    setNewMasterFieldName,
    newMasterFieldKey,
    setNewMasterFieldKey,
    newMasterFieldInputType,
    setNewMasterFieldInputType,
    newMasterFieldRequired,
    setNewMasterFieldRequired,
    newMasterFieldCategory,
    setNewMasterFieldCategory,
    newMasterFieldDescription,
    setNewMasterFieldDescription,
    newMasterFieldOptions,
    setNewMasterFieldOptions,
    newMasterFieldAttributeType,
    setNewMasterFieldAttributeType,
    newMasterFieldMultiColumn,
    setNewMasterFieldMultiColumn,
    newMasterFieldColumnCount,
    setNewMasterFieldColumnCount,
    newMasterFieldColumnNames,
    setNewMasterFieldColumnNames,

    // 핸들러
    handleAddMasterField,
    handleEditMasterField,
    handleUpdateMasterField,
    handleDeleteMasterField,
    resetMasterFieldForm,
  };
}