/**
 * 품목코드 자동생성 훅
 *
 * 품목 유형(FG/PT 등)에 따라 품목코드를 자동 생성
 * - FG: 품목명 그대로 사용
 * - PT-절곡: 품목명+종류+모양길이
 * - PT-조립: 측면규격 기반
 * - PT-구매: 품목명+용량+전원
 * - 기타: 품목명-규격
 */

'use client';

import { useMemo } from 'react';
import type { DynamicFormStructure, DynamicFormData } from '../types';
import type { ItemFieldResponse } from '@/types/item-master-api';
import type { ItemType } from '@/types/item';
import {
  generateItemCode,
  generateAssemblyItemNameSimple,
  generateAssemblySpecification,
  generateBendingItemCodeSimple,
  generatePurchasedItemCode,
} from '../utils/itemCodeGenerator';

// 절곡부품 필드 키 타입
export interface BendingFieldKeys {
  material: string;      // 재질
  category: string;      // 종류
  widthSum: string;      // 폭 합계
  shapeLength: string;   // 모양&길이
  itemName: string;      // 품목명 (절곡부품 코드 생성용)
}

// 조립부품 필드 키 타입
export interface AssemblyFieldKeys {
  sideSpecWidth: string;   // 측면규격 가로
  sideSpecHeight: string;  // 측면규격 세로
  assemblyLength: string;  // 길이
}

// 구매부품 필드 키 타입
export interface PurchasedFieldKeys {
  itemName: string;   // 품목명 (전동개폐기 등)
  capacity: string;   // 용량 (150, 300, etc.)
  power: string;      // 전원 (220V, 380V)
}

// 종류 필드 키 + ID (초기화용)
export interface CategoryKeyWithId {
  key: string;
  id: number;
}

// 훅 반환 타입
export interface ItemCodeGenerationResult {
  // 기본 필드 정보
  hasAutoItemCode: boolean;
  itemNameKey: string;
  allSpecificationKeys: string[];
  statusFieldKey: string;
  activeSpecificationKey: string;

  // 절곡부품 관련
  bendingFieldKeys: BendingFieldKeys;
  autoBendingItemCode: string;
  allCategoryKeysWithIds: CategoryKeyWithId[];

  // 조립부품 관련
  hasAssemblyFields: boolean;
  assemblyFieldKeys: AssemblyFieldKeys;
  autoAssemblyItemName: string;
  autoAssemblySpec: string;

  // 구매부품 관련
  purchasedFieldKeys: PurchasedFieldKeys;
  autoPurchasedItemCode: string;

  // 일반 품목코드 자동생성
  autoGeneratedItemCode: string;
}

// 훅 파라미터 타입
export interface UseItemCodeGenerationParams {
  structure: DynamicFormStructure | null;
  selectedItemType: ItemType | '';
  formData: DynamicFormData;
  isBendingPart: boolean;
  isAssemblyPart: boolean;
  isPurchasedPart: boolean;
  existingItemCodes: string[];
  shouldShowSection: (sectionId: number) => boolean;
  shouldShowField: (fieldId: number) => boolean;
}

/**
 * 품목코드 자동생성 훅
 */
export function useItemCodeGeneration({
  structure,
  selectedItemType,
  formData,
  isBendingPart,
  isAssemblyPart: _isAssemblyPart,
  isPurchasedPart,
  existingItemCodes,
  shouldShowSection,
  shouldShowField,
}: UseItemCodeGenerationParams): ItemCodeGenerationResult {
  // 품목코드 자동생성 관련 필드 정보
  // field_key 또는 field_name 기준으로 품목명/규격 필드 탐지
  const { hasAutoItemCode, itemNameKey, allSpecificationKeys, statusFieldKey } = useMemo(() => {
    if (!structure) return { hasAutoItemCode: false, itemNameKey: '', allSpecificationKeys: [] as string[], statusFieldKey: '' };

    let foundItemNameKey = '';
    let foundStatusFieldKey = '';
    const specificationKeys: string[] = [];

    const checkField = (fieldKey: string, field: ItemFieldResponse) => {
      const fieldName = field.field_name || '';

      // 품목명 필드 탐지 (field_key 또는 field_name 기준)
      const isItemName = fieldKey.includes('item_name') || fieldName.includes('품목명');
      if (isItemName && !foundItemNameKey) {
        foundItemNameKey = fieldKey;
      }

      // 규격 필드 탐지
      const isSpecification = fieldKey.includes('specification') || fieldKey.includes('standard') ||
                             fieldKey.includes('규격') || fieldName.includes('규격') || fieldName.includes('사양');
      if (isSpecification) {
        specificationKeys.push(fieldKey);
      }

      // 품목 상태 필드 탐지
      const isStatusField = fieldKey.includes('is_active') || fieldKey.includes('status') ||
                           fieldKey.includes('active') || fieldName.includes('품목상태') ||
                           fieldName.includes('품목 상태') || fieldName === '상태';
      if (isStatusField && !foundStatusFieldKey) {
        foundStatusFieldKey = fieldKey;
      }
    };

    structure.sections.forEach((section) => {
      section.fields.forEach((f) => {
        const key = f.field.field_key || `field_${f.field.id}`;
        checkField(key, f.field);
      });
    });

    structure.directFields.forEach((f) => {
      const key = f.field.field_key || `field_${f.field.id}`;
      checkField(key, f.field);
    });

    return {
      hasAutoItemCode: !!foundItemNameKey,
      itemNameKey: foundItemNameKey,
      allSpecificationKeys: specificationKeys,
      statusFieldKey: foundStatusFieldKey,
    };
  }, [structure]);

  // 현재 표시 중인 규격 필드 키 (조건부 표시 고려)
  const activeSpecificationKey = useMemo(() => {
    if (!structure || allSpecificationKeys.length === 0) return '';

    // 모든 규격 필드 중 현재 표시 중인 첫 번째 필드 찾기
    for (const section of structure.sections) {
      if (!shouldShowSection(section.section.id)) continue;

      for (const f of section.fields) {
        const fieldKey = f.field.field_key || `field_${f.field.id}`;
        if (!shouldShowField(f.field.id)) continue;
        if (allSpecificationKeys.includes(fieldKey)) {
          return fieldKey;
        }
      }
    }

    // 직접 필드에서도 찾기
    for (const f of structure.directFields) {
      const fieldKey = f.field.field_key || `field_${f.field.id}`;
      if (!shouldShowField(f.field.id)) continue;
      if (allSpecificationKeys.includes(fieldKey)) {
        return fieldKey;
      }
    }

    // 표시 중인 규격 필드가 없으면 첫 번째 규격 필드 반환 (fallback)
    return allSpecificationKeys[0] || '';
  }, [structure, allSpecificationKeys, shouldShowSection, shouldShowField]);

  // 절곡부품 전용 필드 탐지 (재질, 종류, 폭 합계, 모양&길이)
  const { bendingFieldKeys, autoBendingItemCode, allCategoryKeysWithIds } = useMemo(() => {
    if (!structure || selectedItemType !== 'PT' || !isBendingPart) {
      return {
        bendingFieldKeys: {
          material: '',
          category: '',
          widthSum: '',
          shapeLength: '',
          itemName: '',
        },
        autoBendingItemCode: '',
        allCategoryKeysWithIds: [] as CategoryKeyWithId[],
      };
    }

    let materialKey = '';
    const categoryKeysWithIds: CategoryKeyWithId[] = [];
    let widthSumKey = '';
    let shapeLengthKey = '';
    let bendingItemNameKey = '';

    const checkField = (fieldKey: string, field: ItemFieldResponse) => {
      const fieldName = field.field_name || '';
      const lowerKey = fieldKey.toLowerCase();

      // 절곡부품 품목명 필드 탐지 - bending_parts 우선
      const isBendingItemNameField =
        lowerKey.includes('bending_parts') ||
        lowerKey.includes('bending_item') ||
        lowerKey.includes('절곡부품') ||
        lowerKey.includes('절곡_부품') ||
        fieldName.includes('절곡부품') ||
        fieldName.includes('절곡 부품');

      const isGeneralItemNameField =
        lowerKey.includes('item_name') ||
        lowerKey.includes('품목명') ||
        fieldName.includes('품목명') ||
        fieldName === '품목명';

      if (isBendingItemNameField) {
        bendingItemNameKey = fieldKey;
      } else if (isGeneralItemNameField && !bendingItemNameKey) {
        bendingItemNameKey = fieldKey;
      }

      // 재질 필드
      if (lowerKey.includes('material') || lowerKey.includes('재질') ||
          lowerKey.includes('texture') || fieldName.includes('재질')) {
        if (!materialKey) materialKey = fieldKey;
      }

      // 종류 필드 (type_1, type_2, type_3 등 모두 수집)
      if ((lowerKey.includes('category') || lowerKey.includes('종류') ||
          lowerKey.includes('type_') || fieldName === '종류' || fieldName.includes('종류')) &&
          !lowerKey.includes('item_name') && !lowerKey.includes('item_type') &&
          !lowerKey.includes('part_type') && !fieldName.includes('품목명')) {
        categoryKeysWithIds.push({ key: fieldKey, id: field.id });
      }

      // 폭 합계 필드
      if (lowerKey.includes('width_sum') || lowerKey.includes('폭합계') ||
          lowerKey.includes('폭_합계') || lowerKey.includes('width_total') ||
          fieldName.includes('폭 합계') || fieldName.includes('폭합계')) {
        if (!widthSumKey) widthSumKey = fieldKey;
      }

      // 모양&길이 필드
      if (lowerKey.includes('shape_length') || lowerKey.includes('모양') ||
          fieldName.includes('모양') || fieldName.includes('길이')) {
        if (!shapeLengthKey) shapeLengthKey = fieldKey;
      }
    };

    structure.sections.forEach((section) => {
      section.fields.forEach((f) => {
        const key = f.field.field_key || `field_${f.field.id}`;
        checkField(key, f.field);
      });
    });

    structure.directFields.forEach((f) => {
      const key = f.field.field_key || `field_${f.field.id}`;
      checkField(key, f.field);
    });

    // 품목코드 자동생성 (품목명 + 종류 + 모양&길이)
    const effectiveItemNameKey = bendingItemNameKey || itemNameKey;
    const itemNameValue = effectiveItemNameKey ? (formData[effectiveItemNameKey] as string) || '' : '';

    // 종류 필드 선택 - 값이 있는 필드 중 마지막 것을 선택
    let activeCategoryKey = '';
    let categoryValue = '';
    for (const { key: catKey } of categoryKeysWithIds) {
      const val = (formData[catKey] as string) || '';
      if (val) {
        activeCategoryKey = catKey;
        categoryValue = val;
      }
    }

    const shapeLengthValue = shapeLengthKey ? (formData[shapeLengthKey] as string) || '' : '';
    const autoCode = generateBendingItemCodeSimple(itemNameValue, categoryValue, shapeLengthValue);

    return {
      bendingFieldKeys: {
        material: materialKey,
        category: activeCategoryKey,
        widthSum: widthSumKey,
        shapeLength: shapeLengthKey,
        itemName: effectiveItemNameKey,
      },
      autoBendingItemCode: autoCode,
      allCategoryKeysWithIds: categoryKeysWithIds,
    };
  }, [structure, selectedItemType, isBendingPart, formData, itemNameKey]);

  // 조립 부품 필드 탐지 (측면규격 가로/세로, 길이)
  const { hasAssemblyFields, assemblyFieldKeys, autoAssemblyItemName, autoAssemblySpec } = useMemo(() => {
    if (!structure || selectedItemType !== 'PT') {
      return {
        hasAssemblyFields: false,
        assemblyFieldKeys: { sideSpecWidth: '', sideSpecHeight: '', assemblyLength: '' },
        autoAssemblyItemName: '',
        autoAssemblySpec: '',
      };
    }

    let sideSpecWidthKey = '';
    let sideSpecHeightKey = '';
    let assemblyLengthKey = '';

    const checkField = (fieldKey: string, field: ItemFieldResponse) => {
      const fieldName = field.field_name || '';
      const lowerKey = fieldKey.toLowerCase();

      // 측면규격 가로
      const isWidthField = lowerKey.includes('side_spec_width') || lowerKey.includes('sidespecwidth') ||
          fieldName.includes('측면규격(가로)') || fieldName.includes('측면 규격(가로)') ||
          fieldName.includes('측면규격 가로') || fieldName.includes('측면 가로') ||
          (fieldName.includes('측면') && fieldName.includes('가로'));
      if (isWidthField && !sideSpecWidthKey) {
        sideSpecWidthKey = fieldKey;
      }

      // 측면규격 세로
      const isHeightField = lowerKey.includes('side_spec_height') || lowerKey.includes('sidespecheight') ||
          fieldName.includes('측면규격(세로)') || fieldName.includes('측면 규격(세로)') ||
          fieldName.includes('측면규격 세로') || fieldName.includes('측면 세로') ||
          (fieldName.includes('측면') && fieldName.includes('세로'));
      if (isHeightField && !sideSpecHeightKey) {
        sideSpecHeightKey = fieldKey;
      }

      // 길이
      const isLengthField = lowerKey.includes('assembly_length') || lowerKey.includes('assemblylength') ||
          lowerKey === 'length' || lowerKey.endsWith('_length') ||
          fieldName === '길이' || (fieldName.includes('조립') && fieldName.includes('길이'));
      if (isLengthField && !assemblyLengthKey) {
        assemblyLengthKey = fieldKey;
      }
    };

    structure.sections.forEach((section) => {
      section.fields.forEach((f) => {
        const key = f.field.field_key || `field_${f.field.id}`;
        checkField(key, f.field);
      });
    });

    structure.directFields.forEach((f) => {
      const key = f.field.field_key || `field_${f.field.id}`;
      checkField(key, f.field);
    });

    const isAssembly = !!(sideSpecWidthKey && sideSpecHeightKey && assemblyLengthKey);

    // 자동생성 값 계산
    const selectedItemName = itemNameKey ? (formData[itemNameKey] as string) || '' : '';
    const sideSpecWidth = sideSpecWidthKey ? (formData[sideSpecWidthKey] as string) || '' : '';
    const sideSpecHeight = sideSpecHeightKey ? (formData[sideSpecHeightKey] as string) || '' : '';
    const assemblyLength = assemblyLengthKey ? (formData[assemblyLengthKey] as string) || '' : '';

    const autoItemName = generateAssemblyItemNameSimple(selectedItemName, sideSpecWidth, sideSpecHeight);
    const autoSpec = generateAssemblySpecification(sideSpecWidth, sideSpecHeight, assemblyLength);

    return {
      hasAssemblyFields: isAssembly,
      assemblyFieldKeys: {
        sideSpecWidth: sideSpecWidthKey,
        sideSpecHeight: sideSpecHeightKey,
        assemblyLength: assemblyLengthKey,
      },
      autoAssemblyItemName: autoItemName,
      autoAssemblySpec: autoSpec,
    };
  }, [structure, selectedItemType, formData, itemNameKey]);

  // 구매 부품(전동개폐기) 필드 탐지 - 품목명, 용량, 전원
  const { purchasedFieldKeys, autoPurchasedItemCode } = useMemo(() => {
    if (!structure || selectedItemType !== 'PT' || !isPurchasedPart) {
      return {
        purchasedFieldKeys: {
          itemName: '',
          capacity: '',
          power: '',
        },
        autoPurchasedItemCode: '',
      };
    }

    let purchasedItemNameKey = '';
    let capacityKey = '';
    let powerKey = '';

    const checkField = (fieldKey: string, field: ItemFieldResponse) => {
      const fieldName = field.field_name || '';
      const lowerKey = fieldKey.toLowerCase();

      // 구매 부품 품목명 필드 탐지
      const isPurchasedItemNameField = lowerKey.includes('purchaseditemname');
      const isItemNameField =
        isPurchasedItemNameField ||
        lowerKey.includes('item_name') ||
        lowerKey.includes('품목명') ||
        fieldName.includes('품목명') ||
        fieldName === '품목명';

      if (isPurchasedItemNameField) {
        purchasedItemNameKey = fieldKey;
      } else if (isItemNameField && !purchasedItemNameKey) {
        purchasedItemNameKey = fieldKey;
      }

      // 용량 필드 탐지
      const isCapacityField =
        lowerKey.includes('capacity') ||
        lowerKey.includes('용량') ||
        fieldName.includes('용량') ||
        fieldName === '용량';
      if (isCapacityField && !capacityKey) {
        capacityKey = fieldKey;
      }

      // 전원 필드 탐지
      const isPowerField =
        lowerKey.includes('power') ||
        lowerKey.includes('전원') ||
        fieldName.includes('전원') ||
        fieldName === '전원';
      if (isPowerField && !powerKey) {
        powerKey = fieldKey;
      }
    };

    structure.sections.forEach((section) => {
      section.fields.forEach((f) => {
        const key = f.field.field_key || `field_${f.field.id}`;
        checkField(key, f.field);
      });
    });

    structure.directFields.forEach((f) => {
      const key = f.field.field_key || `field_${f.field.id}`;
      checkField(key, f.field);
    });

    const itemNameValue = purchasedItemNameKey ? (formData[purchasedItemNameKey] as string) || '' : '';
    const capacityValue = capacityKey ? (formData[capacityKey] as string) || '' : '';
    const powerValue = powerKey ? (formData[powerKey] as string) || '' : '';

    const autoCode = generatePurchasedItemCode(itemNameValue, capacityValue, powerValue);

    return {
      purchasedFieldKeys: {
        itemName: purchasedItemNameKey,
        capacity: capacityKey,
        power: powerKey,
      },
      autoPurchasedItemCode: autoCode,
    };
  }, [structure, selectedItemType, isPurchasedPart, formData]);

  // 품목코드 자동생성 값 (일반)
  const autoGeneratedItemCode = useMemo(() => {
    if (!hasAutoItemCode) return '';

    const itemName = (formData[itemNameKey] as string) || '';
    const specification = activeSpecificationKey ? (formData[activeSpecificationKey] as string) || '' : '';

    if (!itemName) return '';

    // PT(부품)인 경우: 영문약어-순번 형식 사용
    if (selectedItemType === 'PT') {
      const generatedCode = generateItemCode(itemName, existingItemCodes);
      return generatedCode;
    }

    // 기타 품목: 기존 방식 (품목명-규격)
    if (!specification) return itemName;
    return `${itemName}-${specification}`;
  }, [hasAutoItemCode, itemNameKey, activeSpecificationKey, formData, selectedItemType, existingItemCodes]);

  return {
    // 기본 필드 정보
    hasAutoItemCode,
    itemNameKey,
    allSpecificationKeys,
    statusFieldKey,
    activeSpecificationKey,

    // 절곡부품 관련
    bendingFieldKeys,
    autoBendingItemCode,
    allCategoryKeysWithIds,

    // 조립부품 관련
    hasAssemblyFields,
    assemblyFieldKeys,
    autoAssemblyItemName,
    autoAssemblySpec,

    // 구매부품 관련
    purchasedFieldKeys,
    autoPurchasedItemCode,

    // 일반 품목코드 자동생성
    autoGeneratedItemCode,
  };
}