/**
 * 품목기준관리 Zustand Store 타입 정의
 *
 * 핵심 원칙:
 * 1. 정규화된 상태 구조 (Normalized State)
 * 2. 1곳 수정 → 모든 뷰 자동 업데이트
 * 3. 기존 API 타입과 호환성 유지
 */

// ===== 기본 타입 (API 호환) =====

/** 품목 유형 */
export type ItemType = 'FG' | 'PT' | 'SM' | 'RM' | 'CS';

/** 섹션 타입 */
export type SectionType = 'BASIC' | 'BOM' | 'CUSTOM';

/** 필드 타입 */
import type { ItemFieldType } from '@/types/item-master-api';
export type FieldType = ItemFieldType;

/** 부품 유형 */
export type PartType = 'ASSEMBLY' | 'BENDING' | 'PURCHASED';

/** 재질 유형 */
export type MaterialType = 'STEEL' | 'ALUMINUM' | 'PLASTIC' | 'OTHER';

/** 표면처리 유형 */
export type TreatmentType = 'PAINTING' | 'COATING' | 'PLATING' | 'NONE';

/** 가이드레일 옵션 유형 */
export type GuideRailOptionType = 'MODEL_TYPE' | 'MODEL' | 'CERTIFICATION' | 'SHAPE' | 'FINISH' | 'LENGTH';

// ===== 정규화된 엔티티 타입 =====

/**
 * 페이지 엔티티 (정규화)
 * - sections 배열 대신 sectionIds만 저장
 */
export interface PageEntity {
  id: number;
  tenant_id?: number;
  page_name: string;
  item_type: ItemType;
  description?: string | null;
  absolute_path: string;
  is_active: boolean;
  order_no: number;
  created_by?: number | null;
  updated_by?: number | null;
  created_at: string;
  updated_at: string;
  // 정규화: 섹션 ID만 참조
  sectionIds: number[];
}

/**
 * 섹션 엔티티 (정규화)
 * - fields, bom_items 배열 대신 ID만 저장
 */
export interface SectionEntity {
  id: number;
  tenant_id?: number;
  group_id?: number | null;
  page_id: number | null; // null = 독립 섹션
  title: string;
  section_type: SectionType;
  description?: string | null;
  order_no: number;
  is_template: boolean;
  is_default: boolean;
  is_collapsible?: boolean;
  is_default_open?: boolean;
  created_by?: number | null;
  updated_by?: number | null;
  created_at: string;
  updated_at: string;
  // 정규화: ID만 참조
  fieldIds: number[];
  bomItemIds: number[];
}

/**
 * 필드 엔티티
 */
export interface FieldEntity {
  id: number;
  tenant_id?: number;
  group_id?: number | null;
  section_id: number | null; // null = 독립 필드
  master_field_id?: number | null;
  field_name: string;
  field_key?: string | null;
  field_type: FieldType;
  order_no: number;
  is_required: boolean;
  placeholder?: string | null;
  default_value?: string | null;
  display_condition?: Record<string, unknown> | null;
  validation_rules?: Record<string, unknown> | null;
  options?: Array<{ label: string; value: string }> | null;
  properties?: Record<string, unknown> | null;
  is_locked?: boolean;
  locked_by?: number | null;
  locked_at?: string | null;
  created_by?: number | null;
  updated_by?: number | null;
  created_at: string;
  updated_at: string;
}

/**
 * BOM 아이템 엔티티
 */
export interface BOMItemEntity {
  id: number;
  tenant_id?: number;
  group_id?: number | null;
  section_id: number | null; // null = 독립 BOM
  item_code?: string | null;
  item_name: string;
  quantity: number;
  unit?: string | null;
  unit_price?: number | null;
  total_price?: number | null;
  spec?: string | null;
  note?: string | null;
  created_by?: number | null;
  updated_by?: number | null;
  created_at: string;
  updated_at: string;
}

// ===== 참조 데이터 타입 =====

/** 품목 마스터 */
export interface ItemMasterRef {
  id: string;
  itemCode: string;
  itemName: string;
  itemType: ItemType;
  unit: string;
  isActive?: boolean;
  createdAt: string;
}

/** 규격 마스터 */
export interface SpecificationMasterRef {
  id: string;
  specificationCode: string;
  itemType: 'RM' | 'SM';
  itemName?: string;
  fieldCount: '1' | '2' | '3';
  thickness: string;
  widthA: string;
  widthB?: string;
  widthC?: string;
  length: string;
  description?: string;
  isActive: boolean;
  createdAt?: string;
  updatedAt?: string;
}

/** 원자재/부자재 품목명 마스터 */
export interface MaterialItemNameRef {
  id: string;
  itemType: 'RM' | 'SM';
  itemName: string;
  category?: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 품목 분류 */
export interface ItemCategoryRef {
  id: string;
  categoryType: 'PRODUCT' | 'PART' | 'MATERIAL' | 'SUB_MATERIAL';
  category1: string;
  category2?: string;
  category3?: string;
  code?: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 단위 */
export interface ItemUnitRef {
  id: string;
  unitCode: string;
  unitName: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 재질 */
export interface ItemMaterialRef {
  id: string;
  materialCode: string;
  materialName: string;
  materialType: MaterialType;
  thickness?: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 표면처리 */
export interface SurfaceTreatmentRef {
  id: string;
  treatmentCode: string;
  treatmentName: string;
  treatmentType: TreatmentType;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 부품유형 옵션 */
export interface PartTypeOptionRef {
  id: string;
  partType: PartType;
  optionCode: string;
  optionName: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 부품용도 옵션 */
export interface PartUsageOptionRef {
  id: string;
  usageCode: string;
  usageName: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 가이드레일 옵션 */
export interface GuideRailOptionRef {
  id: string;
  optionType: GuideRailOptionType;
  optionCode: string;
  optionName: string;
  parentOption?: string;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 마스터 필드 (재사용 가능한 필드 템플릿) */
export interface MasterFieldRef {
  id: number;
  tenant_id: number;
  field_name: string;
  field_key?: string | null;
  field_type: FieldType;
  category: string | null;
  description: string | null;
  is_common: boolean;
  is_required?: boolean;
  default_value: string | null;
  options: Array<{ label: string; value: string }> | null;
  validation_rules: Record<string, unknown> | null;
  properties: Record<string, unknown> | null;
  created_by: number | null;
  updated_by: number | null;
  created_at: string;
  updated_at: string;
}

// ===== 스토어 상태 타입 =====

/**
 * 정규화된 엔티티 상태
 */
export interface EntitiesState {
  pages: Record<number, PageEntity>;
  sections: Record<number, SectionEntity>;
  fields: Record<number, FieldEntity>;
  bomItems: Record<number, BOMItemEntity>;
}

/**
 * ID 목록 (순서 관리)
 */
export interface IdsState {
  pages: number[];
  independentSections: number[]; // page_id가 null인 섹션
  independentFields: number[]; // section_id가 null인 필드
  independentBomItems: number[]; // section_id가 null인 BOM
}

/**
 * 참조 데이터 상태
 */
export interface ReferencesState {
  itemMasters: ItemMasterRef[];
  specificationMasters: SpecificationMasterRef[];
  materialItemNames: MaterialItemNameRef[];
  itemCategories: ItemCategoryRef[];
  itemUnits: ItemUnitRef[];
  itemMaterials: ItemMaterialRef[];
  surfaceTreatments: SurfaceTreatmentRef[];
  partTypeOptions: PartTypeOptionRef[];
  partUsageOptions: PartUsageOptionRef[];
  guideRailOptions: GuideRailOptionRef[];
  masterFields: MasterFieldRef[];
}

/**
 * UI 상태
 */
export interface UIState {
  isLoading: boolean;
  error: string | null;
  selectedPageId: number | null;
  selectedSectionId: number | null;
  selectedFieldId: number | null;
}

/**
 * 메인 스토어 상태
 */
export interface ItemMasterState {
  entities: EntitiesState;
  ids: IdsState;
  references: ReferencesState;
  ui: UIState;
}

// ===== 액션 타입 =====

/**
 * 페이지 액션
 */
export interface PageActions {
  loadPages: (pages: PageEntity[]) => void;
  createPage: (page: Omit<PageEntity, 'id' | 'sectionIds' | 'created_at' | 'updated_at'>) => Promise<PageEntity>;
  updatePage: (id: number, updates: Partial<PageEntity>) => Promise<void>;
  deletePage: (id: number) => Promise<void>;
}

/**
 * 섹션 액션
 */
export interface SectionActions {
  loadSections: (sections: SectionEntity[]) => void;
  createSection: (section: Omit<SectionEntity, 'id' | 'fieldIds' | 'bomItemIds' | 'created_at' | 'updated_at'>) => Promise<SectionEntity>;
  createSectionInPage: (pageId: number, section: Omit<SectionEntity, 'id' | 'page_id' | 'fieldIds' | 'bomItemIds' | 'created_at' | 'updated_at'>) => Promise<SectionEntity>;
  updateSection: (id: number, updates: Partial<SectionEntity>) => Promise<void>;
  deleteSection: (id: number) => Promise<void>;
  linkSectionToPage: (sectionId: number, pageId: number) => Promise<void>;
  unlinkSectionFromPage: (sectionId: number) => Promise<void>;
  reorderSections: (pageId: number, dragSectionId: number, hoverSectionId: number) => Promise<void>;
}

/**
 * 필드 액션
 */
export interface FieldActions {
  loadFields: (fields: FieldEntity[]) => void;
  createField: (field: Omit<FieldEntity, 'id' | 'created_at' | 'updated_at'>) => Promise<FieldEntity>;
  createFieldInSection: (sectionId: number, field: Omit<FieldEntity, 'id' | 'section_id' | 'created_at' | 'updated_at'>) => Promise<FieldEntity>;
  updateField: (id: number, updates: Partial<FieldEntity>) => Promise<void>;
  deleteField: (id: number) => Promise<void>;
  linkFieldToSection: (fieldId: number, sectionId: number) => Promise<void>;
  unlinkFieldFromSection: (fieldId: number) => Promise<void>;
  reorderFields: (sectionId: number, dragFieldId: number, hoverFieldId: number) => Promise<void>;
}

/**
 * BOM 액션
 */
export interface BOMActions {
  loadBomItems: (items: BOMItemEntity[]) => void;
  createBomItem: (item: Omit<BOMItemEntity, 'id' | 'created_at' | 'updated_at'>) => Promise<BOMItemEntity>;
  updateBomItem: (id: number, updates: Partial<BOMItemEntity>) => Promise<void>;
  deleteBomItem: (id: number) => Promise<void>;
}

/**
 * UI 액션
 */
export interface UIActions {
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  selectPage: (pageId: number | null) => void;
  selectSection: (sectionId: number | null) => void;
  selectField: (fieldId: number | null) => void;
}

/**
 * 속성(단위/재질/표면처리) CRUD 액션
 */
export interface PropertyActions {
  // 단위 CRUD
  addUnit: (data: {
    unitCode: string;
    unitName: string;
    description?: string;
    isActive?: boolean;
  }) => Promise<ItemUnitRef>;
  updateUnit: (
    id: string,
    updates: {
      unitCode?: string;
      unitName?: string;
      description?: string;
      isActive?: boolean;
    }
  ) => Promise<void>;
  deleteUnit: (id: string) => Promise<void>;

  // 재질 CRUD
  addMaterial: (data: {
    materialCode: string;
    materialName: string;
    materialType: MaterialType;
    thickness?: string;
    description?: string;
    isActive?: boolean;
  }) => Promise<ItemMaterialRef>;
  updateMaterial: (
    id: string,
    updates: {
      materialCode?: string;
      materialName?: string;
      materialType?: MaterialType;
      thickness?: string;
      description?: string;
      isActive?: boolean;
    }
  ) => Promise<void>;
  deleteMaterial: (id: string) => Promise<void>;

  // 표면처리 CRUD
  addTreatment: (data: {
    treatmentCode: string;
    treatmentName: string;
    treatmentType: TreatmentType;
    description?: string;
    isActive?: boolean;
  }) => Promise<SurfaceTreatmentRef>;
  updateTreatment: (
    id: string,
    updates: {
      treatmentCode?: string;
      treatmentName?: string;
      treatmentType?: TreatmentType;
      description?: string;
      isActive?: boolean;
    }
  ) => Promise<void>;
  deleteTreatment: (id: string) => Promise<void>;

  // 섹션 복제
  cloneSection: (sectionId: number) => Promise<SectionEntity>;
}

/**
 * 전체 스토어 타입
 */
export interface ItemMasterStore extends ItemMasterState {
  // 페이지 액션
  loadPages: PageActions['loadPages'];
  createPage: PageActions['createPage'];
  updatePage: PageActions['updatePage'];
  deletePage: PageActions['deletePage'];

  // 섹션 액션
  loadSections: SectionActions['loadSections'];
  createSection: SectionActions['createSection'];
  createSectionInPage: SectionActions['createSectionInPage'];
  updateSection: SectionActions['updateSection'];
  deleteSection: SectionActions['deleteSection'];
  linkSectionToPage: SectionActions['linkSectionToPage'];
  unlinkSectionFromPage: SectionActions['unlinkSectionFromPage'];
  reorderSections: SectionActions['reorderSections'];

  // 필드 액션
  loadFields: FieldActions['loadFields'];
  createField: FieldActions['createField'];
  createFieldInSection: FieldActions['createFieldInSection'];
  updateField: FieldActions['updateField'];
  deleteField: FieldActions['deleteField'];
  linkFieldToSection: FieldActions['linkFieldToSection'];
  unlinkFieldFromSection: FieldActions['unlinkFieldFromSection'];
  reorderFields: FieldActions['reorderFields'];

  // BOM 액션
  loadBomItems: BOMActions['loadBomItems'];
  createBomItem: BOMActions['createBomItem'];
  updateBomItem: BOMActions['updateBomItem'];
  deleteBomItem: BOMActions['deleteBomItem'];

  // UI 액션
  setLoading: UIActions['setLoading'];
  setError: UIActions['setError'];
  selectPage: UIActions['selectPage'];
  selectSection: UIActions['selectSection'];
  selectField: UIActions['selectField'];

  // 속성 CRUD 액션
  addUnit: PropertyActions['addUnit'];
  updateUnit: PropertyActions['updateUnit'];
  deleteUnit: PropertyActions['deleteUnit'];
  addMaterial: PropertyActions['addMaterial'];
  updateMaterial: PropertyActions['updateMaterial'];
  deleteMaterial: PropertyActions['deleteMaterial'];
  addTreatment: PropertyActions['addTreatment'];
  updateTreatment: PropertyActions['updateTreatment'];
  deleteTreatment: PropertyActions['deleteTreatment'];
  cloneSection: PropertyActions['cloneSection'];

  // 초기화
  reset: () => void;

  // API 연동
  initFromApi: () => Promise<void>;
}

// ===== 파생 상태 (Denormalized) 타입 =====

/**
 * 계층구조 뷰용 페이지 (섹션/필드 포함)
 */
export interface PageWithDetails {
  id: number;
  page_name: string;
  item_type: ItemType;
  description?: string | null;
  is_active: boolean;
  order_no: number;
  sections: SectionWithDetails[];
}

/**
 * 계층구조 뷰용 섹션 (필드/BOM 포함)
 */
export interface SectionWithDetails {
  id: number;
  title: string;
  section_type: SectionType;
  page_id: number | null;
  order_no: number;
  is_collapsible?: boolean;
  is_default_open?: boolean;
  fields: FieldEntity[];
  bom_items: BOMItemEntity[];
}