'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { useItemMaster } from '@/contexts/ItemMasterContext';
import { useErrorAlert } from '../contexts';
import type { ItemPage, ItemField, ItemMasterField, FieldDisplayCondition } from '@/contexts/ItemMasterContext';
import { type ConditionalFieldConfig } from '../components/ConditionalDisplayUI';
import { fieldService } 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';

// 입력 모드 타입: 'new'/'existing' 또는 'custom'/'master' 모두 지원
type FieldInputModeType = 'new' | 'existing' | 'custom' | 'master';

export interface UseFieldManagementReturn {
  // 다이얼로그 상태
  isFieldDialogOpen: boolean;
  setIsFieldDialogOpen: (open: boolean) => void;
  selectedSectionForField: number | null;
  setSelectedSectionForField: (id: number | null) => void;
  editingFieldId: number | null;
  setEditingFieldId: (id: number | null) => void;

  // 입력 모드
  fieldInputMode: FieldInputModeType;
  setFieldInputMode: (mode: FieldInputModeType) => void;
  showMasterFieldList: boolean;
  setShowMasterFieldList: (show: boolean) => void;
  // string 또는 number | null 모두 지원
  selectedMasterFieldId: string | number | null;
  setSelectedMasterFieldId: (id: string | number | null) => void;

  // 필드 폼 상태
  newFieldName: string;
  setNewFieldName: (name: string) => void;
  newFieldKey: string;
  setNewFieldKey: (key: string) => void;
  // string 타입으로 유연하게 처리
  newFieldInputType: string;
  setNewFieldInputType: (type: string) => void;
  newFieldRequired: boolean;
  setNewFieldRequired: (required: boolean) => void;
  newFieldOptions: string;
  setNewFieldOptions: (options: string) => void;
  newFieldDescription: string;
  setNewFieldDescription: (desc: string) => void;

  // 텍스트박스 컬럼
  textboxColumns: Array<{ id: string; name: string; key: string }>;
  setTextboxColumns: React.Dispatch<React.SetStateAction<Array<{ id: string; name: string; key: string }>>>;
  isColumnDialogOpen: boolean;
  setIsColumnDialogOpen: (open: boolean) => void;
  editingColumnId: string | null;
  setEditingColumnId: (id: string | null) => void;
  columnName: string;
  setColumnName: (name: string) => void;
  columnKey: string;
  setColumnKey: (key: string) => void;

  // 조건부 필드
  newFieldConditionEnabled: boolean;
  setNewFieldConditionEnabled: (enabled: boolean) => void;
  newFieldConditionTargetType: 'field' | 'section';
  setNewFieldConditionTargetType: (type: 'field' | 'section') => void;
  newFieldConditionFields: ConditionalFieldConfig[];
  setNewFieldConditionFields: React.Dispatch<React.SetStateAction<ConditionalFieldConfig[]>>;
  newFieldConditionSections: string[];
  setNewFieldConditionSections: React.Dispatch<React.SetStateAction<string[]>>;
  tempConditionValue: string;
  setTempConditionValue: (value: string) => void;

  // 핸들러
  handleAddField: (selectedPage: ItemPage | undefined) => Promise<void>;
  handleEditField: (sectionId: string, field: ItemField) => void;
  handleDeleteField: (pageId: string, sectionId: string, fieldId: string) => void;
  resetFieldForm: () => void;
}

export function useFieldManagement(): UseFieldManagementReturn {
  const {
    itemMasterFields,
    addFieldToSection,
    updateField,
    deleteField,
    addItemMasterField: _addItemMasterField, // 2025-11-27: 중복 필드 생성 방지로 사용 안함
    updateItemMasterField,
  } = useItemMaster();

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

  // 다이얼로그 상태
  const [isFieldDialogOpen, setIsFieldDialogOpen] = useState(false);
  const [selectedSectionForField, setSelectedSectionForField] = useState<number | null>(null);
  const [editingFieldId, setEditingFieldId] = useState<number | null>(null);

  // 입력 모드
  const [fieldInputMode, setFieldInputMode] = useState<FieldInputModeType>('custom');
  const [showMasterFieldList, setShowMasterFieldList] = useState(false);
  const [selectedMasterFieldId, setSelectedMasterFieldId] = useState<string | number | null>('');

  // 필드 폼 상태
  const [newFieldName, setNewFieldName] = useState('');
  const [newFieldKey, setNewFieldKey] = useState('');
  const [newFieldInputType, setNewFieldInputType] = useState<string>('textbox');
  const [newFieldRequired, setNewFieldRequired] = useState(false);
  const [newFieldOptions, setNewFieldOptions] = useState('');
  const [newFieldDescription, setNewFieldDescription] = useState('');

  // 텍스트박스 컬럼
  const [textboxColumns, setTextboxColumns] = useState<Array<{ id: string; name: string; key: string }>>([]);
  const [isColumnDialogOpen, setIsColumnDialogOpen] = useState(false);
  const [editingColumnId, setEditingColumnId] = useState<string | null>(null);
  const [columnName, setColumnName] = useState('');
  const [columnKey, setColumnKey] = useState('');

  // 조건부 필드
  const [newFieldConditionEnabled, setNewFieldConditionEnabled] = useState(false);
  const [newFieldConditionTargetType, setNewFieldConditionTargetType] = useState<'field' | 'section'>('field');
  const [newFieldConditionFields, setNewFieldConditionFields] = useState<ConditionalFieldConfig[]>([]);
  const [newFieldConditionSections, setNewFieldConditionSections] = useState<string[]>([]);
  const [tempConditionValue, setTempConditionValue] = useState('');

  // 마스터 필드 선택 시 폼 자동 채우기
  useEffect(() => {
    if (fieldInputMode === 'master' && selectedMasterFieldId) {
      const masterField = itemMasterFields.find(f => f.id === Number(selectedMasterFieldId));
      if (masterField) {
        setNewFieldName(masterField.field_name);
        // 2025-12-04: master 모드에서 field_key를 field_{id} 형태로 설정 (백엔드 검증 통과용)
        setNewFieldKey(`field_${selectedMasterFieldId}`);
        setNewFieldInputType(masterField.field_type || 'textbox');
        // properties에서 required 확인, 또는 validation_rules에서 확인
        const isRequired = (masterField.properties as any)?.required || false;
        setNewFieldRequired(isRequired);
        setNewFieldOptions(masterField.options?.map(o => o.label).join(', ') || '');
        setNewFieldDescription(masterField.description || '');
      }
    } else if (fieldInputMode === 'custom') {
      // 직접 입력 모드로 전환 시 폼 초기화
      setNewFieldName('');
      setNewFieldKey('');
      setNewFieldInputType('textbox');
      setNewFieldRequired(false);
      setNewFieldOptions('');
      setNewFieldDescription('');
    }
  }, [fieldInputMode, selectedMasterFieldId, itemMasterFields]);

  // 필드 추가 (2025-11-27: async/await 추가 - 다른 탭 실시간 동기화)
  const handleAddField = async (selectedPage: ItemPage | undefined) => {

    if (!selectedPage || !selectedSectionForField || !newFieldName.trim() || !newFieldKey.trim()) {
      toast.error('모든 필수 항목을 입력해주세요');
      return;
    }

    // 조건부 표시 설정
    // 2025-12-02: ConditionalDisplayUI는 field/section 모두 newFieldConditionFields에 저장
    // - field 모드: fieldConditions[].targetFieldIds에 필드 ID 저장
    // - section 모드: fieldConditions[].targetSectionIds에 섹션 ID 저장
    const displayCondition: FieldDisplayCondition | undefined = newFieldConditionEnabled
      ? {
          targetType: newFieldConditionTargetType,
          fieldConditions: newFieldConditionFields.length > 0
            ? newFieldConditionFields
            : undefined,
        }
      : undefined;

    // 텍스트박스 컬럼 설정
    const hasColumns = newFieldInputType === 'textbox' && textboxColumns.length > 0;

    // 마스터 항목에서 가져온 경우 master_field_id 설정
    const masterFieldId = fieldInputMode === 'master' && selectedMasterFieldId
      ? Number(selectedMasterFieldId)
      : null;

    const newField: ItemField = {
      id: editingFieldId ? Number(editingFieldId) : Date.now(),
      section_id: Number(selectedSectionForField),
      master_field_id: masterFieldId,
      field_name: newFieldName,
      field_key: newFieldKey, // 2025-11-28: field_key 추가 (백엔드에서 {ID}_{입력값} 형태로 저장)
      field_type: newFieldInputType as FieldTypeValue,
      order_no: 0,
      is_required: newFieldRequired,
      placeholder: newFieldDescription || null,
      default_value: null,
      display_condition: displayCondition as Record<string, any> | null || null,
      validation_rules: null,
      options: newFieldInputType === 'dropdown' && newFieldOptions.trim()
        ? newFieldOptions.split(',').map(o => ({ label: o.trim(), value: o.trim() }))
        : null,
      properties: hasColumns ? {
        multiColumn: true,
        columnCount: textboxColumns.length,
        columnNames: textboxColumns.map(c => c.name)
      } : null,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    };

    try {
      if (editingFieldId) {
        await updateField(Number(editingFieldId), newField);

        // 항목관리 탭의 마스터 항목도 업데이트 (동일한 fieldKey가 있으면)
        const existingMasterField = itemMasterFields.find(mf => mf.id.toString() === newField.field_name);
        if (existingMasterField) {
          const updatedMasterField: Partial<ItemMasterField> = {
            field_name: newField.field_name,
            description: newField.placeholder ?? null,
            properties: newField.properties,
            updated_at: new Date().toISOString()
          };
          await updateItemMasterField(existingMasterField.id, updatedMasterField);
        }

        toast.success('항목이 섹션에 수정되었습니다!');
      } else {

        // 섹션에 항목 추가 (await로 완료 대기)
        // 2025-11-27: addItemMasterField 호출 제거 - 중복 필드 생성 방지
        // 계층구조에서 만든 필드는 섹션에만 연결됨 (section_id = X)
        // 항목탭에는 독립 필드(section_id = null)만 표시
        await addFieldToSection(Number(selectedSectionForField), newField);

        toast.success('항목이 섹션에 추가되었습니다!');
      }

      resetFieldForm();
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('필드 처리 실패:', error);

      // 422 ValidationException 상세 메시지 처리 (field_key 중복/예약어, field_name 중복 등)
      if (error instanceof ApiError) {
        // errors 객체에서 첫 번째 에러 메시지 추출 → AlertDialog로 표시
        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('항목 처리에 실패했습니다', '오류');
      }
    }
  };

  // 필드 수정
  const handleEditField = (sectionId: string, field: ItemField) => {
    setSelectedSectionForField(Number(sectionId));
    setEditingFieldId(field.id);

    // fieldService를 사용하여 폼 데이터 변환
    const formData = fieldService.toFormData(field);
    setNewFieldName(formData.name);
    setNewFieldKey(formData.key);
    setNewFieldInputType(formData.inputType);
    setNewFieldRequired(formData.required);
    setNewFieldOptions(formData.options);
    setNewFieldDescription(formData.description);

    // 조건부 표시 설정 로드
    if (field.display_condition) {
      setNewFieldConditionEnabled(true);
      setNewFieldConditionTargetType(field.display_condition.targetType);
      setNewFieldConditionFields(field.display_condition.fieldConditions || []);
      setNewFieldConditionSections(field.display_condition.sectionIds || []);
    } else {
      setNewFieldConditionEnabled(false);
      setNewFieldConditionTargetType('field');
      setNewFieldConditionFields([]);
      setNewFieldConditionSections([]);
    }

    setIsFieldDialogOpen(true);
  };

  // 필드 삭제
  const handleDeleteField = (pageId: string, sectionId: string, fieldId: string) => {
    deleteField(Number(fieldId));
  };

  // 폼 초기화
  const resetFieldForm = () => {
    setNewFieldName('');
    setNewFieldKey('');
    setNewFieldInputType('textbox');
    setNewFieldRequired(false);
    setNewFieldOptions('');
    setNewFieldDescription('');
    setNewFieldConditionEnabled(false);
    setNewFieldConditionTargetType('field');
    setNewFieldConditionFields([]);
    setNewFieldConditionSections([]);
    setTempConditionValue('');
    setEditingFieldId(null);
    setSelectedSectionForField(null);
    setFieldInputMode('custom');
    setSelectedMasterFieldId('');
    setTextboxColumns([]);
    setIsFieldDialogOpen(false);
  };

  return {
    // 다이얼로그 상태
    isFieldDialogOpen,
    setIsFieldDialogOpen,
    selectedSectionForField,
    setSelectedSectionForField,
    editingFieldId,
    setEditingFieldId,

    // 입력 모드
    fieldInputMode,
    setFieldInputMode,
    showMasterFieldList,
    setShowMasterFieldList,
    selectedMasterFieldId,
    setSelectedMasterFieldId,

    // 필드 폼 상태
    newFieldName,
    setNewFieldName,
    newFieldKey,
    setNewFieldKey,
    newFieldInputType,
    setNewFieldInputType,
    newFieldRequired,
    setNewFieldRequired,
    newFieldOptions,
    setNewFieldOptions,
    newFieldDescription,
    setNewFieldDescription,

    // 텍스트박스 컬럼
    textboxColumns,
    setTextboxColumns,
    isColumnDialogOpen,
    setIsColumnDialogOpen,
    editingColumnId,
    setEditingColumnId,
    columnName,
    setColumnName,
    columnKey,
    setColumnKey,

    // 조건부 필드
    newFieldConditionEnabled,
    setNewFieldConditionEnabled,
    newFieldConditionTargetType,
    setNewFieldConditionTargetType,
    newFieldConditionFields,
    setNewFieldConditionFields,
    newFieldConditionSections,
    setNewFieldConditionSections,
    tempConditionValue,
    setTempConditionValue,

    // 핸들러
    handleAddField,
    handleEditField,
    handleDeleteField,
    resetFieldForm,
  };
}