/**
 * pop-field 타입 정의
 * 섹션 기반 멀티필드: 하나의 컴포넌트 안에 여러 섹션, 각 섹션에 여러 필드
 * 저장용 값 입력 (text/number/date/select/auto/numpad)
 */

import type { DataSourceFilter } from "../types";

// ===== 서브타입 =====

export type FieldInputType = "text" | "number" | "date" | "select" | "auto" | "numpad";

export const FIELD_INPUT_TYPE_LABELS: Record<FieldInputType, string> = {
  text: "텍스트",
  number: "숫자",
  date: "날짜",
  select: "선택",
  auto: "자동채번",
  numpad: "숫자패드",
};

// ===== 섹션 스타일 =====

export type FieldSectionStyle = "display" | "input";

export const FIELD_SECTION_STYLE_LABELS: Record<FieldSectionStyle, string> = {
  display: "읽기 폼",
  input: "입력 폼",
};

// 섹션 커스텀 외관 옵션
export interface FieldSectionAppearance {
  bgColor?: string;
  borderColor?: string;
  textColor?: string;
}

export const DEFAULT_SECTION_APPEARANCES: Record<FieldSectionStyle, FieldSectionAppearance> = {
  display: { bgColor: "bg-emerald-50", borderColor: "border-emerald-200", textColor: "text-foreground" },
  input: { bgColor: "bg-background", borderColor: "border-border", textColor: "text-foreground" },
};

// ===== select 옵션 소스 =====

export type FieldSelectSourceType = "static" | "table";

export interface SelectLinkedFilter {
  sourceFieldId: string;
  filterColumn: string;
}

export interface FieldSelectSource {
  type: FieldSelectSourceType;
  staticOptions?: { value: string; label: string }[];
  tableName?: string;
  valueColumn?: string;
  labelColumn?: string;
  filters?: DataSourceFilter[];
  linkedFilters?: SelectLinkedFilter[];
}

// ===== 자동 채번 설정 =====

export interface AutoNumberConfig {
  prefix?: string;
  dateFormat?: string;
  separator?: string;
  sequenceDigits?: number;
  numberingRuleId?: string;
}

// ===== 유효성 검증 =====

export interface PopFieldValidation {
  required?: boolean;
  min?: number;
  max?: number;
  pattern?: string;
  customMessage?: string;
}

// ===== 개별 필드 정의 =====

export interface PopFieldItem {
  id: string;
  inputType: FieldInputType;
  fieldName: string;
  labelText?: string;
  placeholder?: string;
  defaultValue?: unknown;
  readOnly?: boolean;
  unit?: string;

  selectSource?: FieldSelectSource;
  autoNumber?: AutoNumberConfig;
  validation?: PopFieldValidation;
}

// ===== 섹션 정의 =====

export interface PopFieldSection {
  id: string;
  label?: string;
  style: FieldSectionStyle;
  columns: "auto" | 1 | 2 | 3 | 4;
  showLabels: boolean;
  appearance?: FieldSectionAppearance;
  fields: PopFieldItem[];
}

// ===== 저장 설정: 값 소스 타입 =====

export type FieldValueSource = "direct" | "json_extract" | "db_column";

export const FIELD_VALUE_SOURCE_LABELS: Record<FieldValueSource, string> = {
  direct: "직접 입력",
  json_extract: "JSON 추출",
  db_column: "DB 컬럼",
};

// ===== 저장 설정: 필드-컬럼 매핑 =====

export interface PopFieldSaveMapping {
  fieldId: string;
  valueSource: FieldValueSource;
  targetColumn: string;
  sourceJsonColumn?: string;
  sourceJsonKey?: string;
}

// ===== 숨은 필드 매핑 (UI에 미표시, 전달 데이터에서 추출하여 저장) =====

export type HiddenValueSource = "json_extract" | "db_column" | "static";

export interface PopFieldHiddenMapping {
  id: string;
  label?: string;
  valueSource: HiddenValueSource;
  sourceJsonColumn?: string;
  sourceJsonKey?: string;
  sourceDbColumn?: string;
  staticValue?: string;
  targetColumn: string;
}

// ===== 자동생성 필드 (서버 채번규칙으로 저장 시점 생성) =====

export interface PopFieldAutoGenMapping {
  id: string;
  linkedFieldId?: string;
  label: string;
  targetColumn: string;
  numberingRuleId?: string;
  showInForm: boolean;
  showResultModal: boolean;
  shareAcrossItems?: boolean;
}

export interface PopFieldSaveConfig {
  tableName: string;
  fieldMappings: PopFieldSaveMapping[];
  hiddenMappings?: PopFieldHiddenMapping[];
  autoGenMappings?: PopFieldAutoGenMapping[];
}

// ===== 읽기 데이터 소스 =====

export interface PopFieldReadMapping {
  fieldId: string;
  valueSource: FieldValueSource;
  columnName: string;
  jsonKey?: string;
}

export interface PopFieldReadSource {
  tableName: string;
  pkColumn: string;
  fieldMappings: PopFieldReadMapping[];
}

// ===== pop-field 전체 설정 (루트) =====

export interface PopFieldConfig {
  targetTable?: string;
  sections: PopFieldSection[];
  saveConfig?: PopFieldSaveConfig;
  readSource?: PopFieldReadSource;
}

// ===== 기본값 =====

export const DEFAULT_FIELD_CONFIG: PopFieldConfig = {
  targetTable: "",
  sections: [
    {
      id: "section_display",
      label: "요약",
      style: "display",
      columns: "auto",
      showLabels: true,
      fields: [
        { id: "f_disp_1", inputType: "text", fieldName: "", labelText: "항목1", readOnly: true },
        { id: "f_disp_2", inputType: "text", fieldName: "", labelText: "항목2", readOnly: true },
      ],
    },
    {
      id: "section_input",
      label: "입력",
      style: "input",
      columns: "auto",
      showLabels: true,
      fields: [
        { id: "f_input_1", inputType: "text", fieldName: "", labelText: "필드1" },
        { id: "f_input_2", inputType: "number", fieldName: "", labelText: "필드2", unit: "EA" },
      ],
    },
  ],
};
