"use client";

import { ComponentConfig } from "@/types/component";
import type { FieldConfig } from "@/types/invyone-component";

/**
 * Table 컴포넌트 통합 설정 타입
 *
 * 9개의 기존 테이블 계열 컴포넌트를 통합한 **범용 데이터 테이블**.
 * displayMode 로 변형 (기본/분할/그룹/피벗).
 *
 * 흡수 대상 (9):
 *   - v2-table-list (base, 기본 테이블)
 *   - v2-table-grouped (그룹핑 테이블)
 *   - v2-pivot-grid (피벗 그리드)
 *   - v2-split-panel-layout (좌우 분할: 목록 | 상세)
 *   - table-list, split-panel-layout, split-panel-layout2 (legacy)
 *   - modal-repeater-table, simple-repeater-table (legacy)
 *   - tax-invoice-list, pivot-grid (legacy)
 */

export type TableDisplayMode = "table" | "split" | "grouped" | "pivot" | "card";
export type TableSelectionMode = "none" | "single" | "multiple";
export type TableRowHeight = "compact" | "normal" | "relaxed";

export interface TableColumn {
  /** 컬럼 키 (데이터 필드명) */
  key: string;
  /** 컬럼 라벨 */
  label: string;
  /** 너비 (px) */
  width?: number;
  /** 정렬 */
  align?: "left" | "center" | "right";
  /** 정렬 가능 여부 */
  sortable?: boolean;
  /** 포맷 */
  format?: string;
  /** 표시 여부 */
  visible?: boolean;
}

export interface TablePagination {
  enabled?: boolean;
  pageSize?: number;
  showSizeSelector?: boolean;
  pageSizeOptions?: number[];
}

// ─── card 모드 보조 타입 ─────────────────────────────────────────────

export interface TableCardStyleConfig {
  showTitle?: boolean;
  showSubtitle?: boolean;
  showDescription?: boolean;
  showImage?: boolean;
  maxDescriptionLength?: number;
  imagePosition?: "top" | "left" | "right";
  imageSize?: "small" | "medium" | "large";
  showActions?: boolean;
  showViewButton?: boolean;
  showEditButton?: boolean;
  showDeleteButton?: boolean;
}

export interface TableCardColumnMapping {
  titleColumn?: string;
  subtitleColumn?: string;
  descriptionColumn?: string;
  imageColumn?: string;
  /** 본문에 한 줄씩 더 노출할 컬럼들 */
  displayColumns?: string[];
  /** 액션 버튼 셀로 표시할 컬럼들 */
  actionColumns?: string[];
}

// ─── pivot 모드 풍부한 필드 정의 ───────────────────────────────────

export type PivotAreaType = "row" | "column" | "data" | "filter";
export type PivotAggregationType =
  | "sum"
  | "count"
  | "avg"
  | "min"
  | "max"
  | "countDistinct";
export type PivotSummaryDisplayMode =
  | "absoluteValue"
  | "percentOfColumnTotal"
  | "percentOfRowTotal"
  | "percentOfGrandTotal"
  | "percentOfColumnGrandTotal"
  | "percentOfRowGrandTotal"
  | "runningTotalByRow"
  | "runningTotalByColumn"
  | "differenceFromPrevious"
  | "percentDifferenceFromPrevious";
export type PivotDateGroupInterval = "year" | "quarter" | "month" | "week" | "day";
export type PivotSortDirection = "asc" | "desc" | "none";
export type PivotFieldDataType = "string" | "number" | "date" | "boolean";

export interface PivotFieldFormat {
  type: "number" | "currency" | "percent" | "date" | "text";
  precision?: number;
  thousandSeparator?: boolean;
  prefix?: string;
  suffix?: string;
  dateFormat?: string;
}

export interface PivotFieldConfig {
  field: string;
  caption: string;
  area: PivotAreaType;
  areaIndex?: number;
  dataType?: PivotFieldDataType;
  summaryType?: PivotAggregationType;
  summaryDisplayMode?: PivotSummaryDisplayMode;
  showValuesAs?: PivotSummaryDisplayMode;
  sortBy?: "value" | "caption";
  sortOrder?: PivotSortDirection;
  sortBySummary?: string;
  groupInterval?: PivotDateGroupInterval;
  groupName?: string;
  visible?: boolean;
  width?: number;
  expanded?: boolean;
  format?: PivotFieldFormat;
  // 필터 설정 (filter area)
  filterValues?: any[];
  filterType?: "include" | "exclude";
  // 계산 필드 (수식 기반)
  isCalculated?: boolean;
  calculateFormula?: string;
}

// ─── pivot 결과 데이터 구조 (utils/pivot 가 사용) ─────────────────

export interface PivotCellValue {
  field: string;
  value: number | null;
  formattedValue: string;
}

export interface PivotHeaderNode {
  value: any;
  caption: string;
  level: number;
  children?: PivotHeaderNode[];
  isExpanded: boolean;
  path: string[];
  subtotal?: PivotCellValue[];
  span?: number;
}

export interface PivotFlatRow {
  path: string[];
  level: number;
  caption: string;
  isExpanded: boolean;
  hasChildren: boolean;
  isTotal?: boolean;
}

export interface PivotFlatColumn {
  path: string[];
  level: number;
  caption: string;
  span: number;
  isTotal?: boolean;
}

export interface PivotResult {
  rowHeaders: PivotHeaderNode[];
  columnHeaders: PivotHeaderNode[];
  dataMatrix: Map<string, PivotCellValue[]>;
  flatRows: PivotFlatRow[];
  flatColumns: PivotFlatColumn[];
  grandTotals: {
    row: Map<string, PivotCellValue[]>;
    column: Map<string, PivotCellValue[]>;
    grand: PivotCellValue[];
  };
}

export interface PivotCellData {
  value: any;
  rowPath: string[];
  columnPath: string[];
  field?: string;
  aggregationType?: PivotAggregationType;
  isTotal?: boolean;
  isGrandTotal?: boolean;
}

// ─── pivot 표시 / 차트 / 조건부 서식 / 데이터 소스 (본체가 사용) ────

export type PivotDataSourceType = "table" | "api" | "static";

export interface PivotFilterCondition {
  field: string;
  operator: "=" | "!=" | ">" | "<" | ">=" | "<=" | "LIKE" | "IN";
  value?: any;
  valueFromField?: string;
}

export interface PivotJoinConfig {
  joinType: "INNER" | "LEFT" | "RIGHT";
  targetTable: string;
  sourceColumn: string;
  targetColumn: string;
  columns: string[];
}

export interface PivotDataSourceConfig {
  type: PivotDataSourceType;
  tableName?: string;
  apiEndpoint?: string;
  apiMethod?: "GET" | "POST";
  staticData?: any[];
  filterConditions?: PivotFilterCondition[];
  joinConfigs?: PivotJoinConfig[];
}

export interface PivotTotalsConfig {
  showRowGrandTotals?: boolean;
  showRowTotals?: boolean;
  rowTotalsPosition?: "first" | "last";
  rowGrandTotalPosition?: "top" | "bottom";
  showColumnGrandTotals?: boolean;
  showColumnTotals?: boolean;
  columnTotalsPosition?: "first" | "last";
  columnGrandTotalPosition?: "left" | "right";
}

export interface PivotFieldChooserConfig {
  enabled: boolean;
  allowSearch?: boolean;
  layout?: "default" | "simplified";
  height?: number;
  applyChangesMode?: "instantly" | "onDemand";
}

export interface PivotChartConfig {
  enabled: boolean;
  type: "bar" | "line" | "area" | "pie" | "stackedBar";
  position: "top" | "bottom" | "left" | "right";
  height?: number;
  showLegend?: boolean;
  animate?: boolean;
}

export interface PivotConditionalFormatRule {
  id: string;
  type: "colorScale" | "dataBar" | "iconSet" | "cellValue";
  field?: string;
  colorScale?: {
    minColor: string;
    midColor?: string;
    maxColor: string;
  };
  dataBar?: {
    color: string;
    showValue?: boolean;
    minValue?: number;
    maxValue?: number;
  };
  iconSet?: {
    type: "arrows" | "traffic" | "rating" | "flags";
    thresholds: number[];
    reverse?: boolean;
  };
  cellValue?: {
    operator: ">" | ">=" | "<" | "<=" | "=" | "!=" | "between";
    value1: number;
    value2?: number;
    backgroundColor?: string;
    textColor?: string;
    bold?: boolean;
  };
}

export interface PivotStyleConfig {
  theme: "default" | "compact" | "modern";
  headerStyle: "default" | "dark" | "light";
  cellPadding: "compact" | "normal" | "comfortable";
  borderStyle: "none" | "light" | "heavy";
  alternateRowColors?: boolean;
  highlightTotals?: boolean;
  conditionalFormats?: PivotConditionalFormatRule[];
  mergeCells?: boolean;
}

export interface PivotExportConfig {
  excel?: boolean;
  pdf?: boolean;
  fileName?: string;
}

export interface PivotGridState {
  expandedRowPaths: string[][];
  expandedColumnPaths: string[][];
  sortConfig: {
    field: string;
    direction: PivotSortDirection;
  } | null;
  filterConfig: Record<string, any[]>;
}

// pivot 본체 props (PivotView 가 받음)
export interface PivotGridProps {
  id?: string;
  title?: string;
  dataSource?: PivotDataSourceConfig;
  fields?: PivotFieldConfig[];
  totals?: PivotTotalsConfig;
  style?: PivotStyleConfig;
  fieldChooser?: PivotFieldChooserConfig;
  chart?: PivotChartConfig;
  allowSortingBySummary?: boolean;
  allowFiltering?: boolean;
  allowExpandAll?: boolean;
  wordWrapEnabled?: boolean;
  height?: string | number;
  maxHeight?: string;
  stateStoring?: {
    enabled: boolean;
    storageKey?: string;
  };
  exportConfig?: PivotExportConfig;
  data?: any[];
  onCellClick?: (cellData: PivotCellData) => void;
  onCellDoubleClick?: (cellData: PivotCellData) => void;
  onFieldDrop?: (field: PivotFieldConfig, targetArea: PivotAreaType) => void;
  onExpandChange?: (expandedPaths: string[][]) => void;
  onDataChange?: (data: any[]) => void;
}

export interface TableConfig extends ComponentConfig {
  /** 연결된 테이블명 (DB) */
  selectedTable?: string;
  /** 표시 모드 (기본/분할/그룹/피벗/카드) */
  displayMode?: TableDisplayMode;
  /** 컬럼 설정 */
  columns?: TableColumn[];
  /** FieldConfig 기반 컬럼 자동 생성 (선택) */
  fields?: FieldConfig[];
  /** 행 선택 모드 */
  selectionMode?: TableSelectionMode;
  /** 체크박스 컬럼 */
  showCheckbox?: boolean;
  /** 헤더 표시 */
  showHeader?: boolean;
  /** 푸터 표시 */
  showFooter?: boolean;
  /** 페이지네이션 */
  pagination?: TablePagination;
  /** 행 높이 */
  rowHeight?: TableRowHeight;
  /** 줄무늬 (홀수/짝수 다른 색) */
  striped?: boolean;
  /** 호버 효과 */
  hoverable?: boolean;
  /** 테두리 */
  bordered?: boolean;

  // ─── split 모드 전용 ───
  /** split 모드: 좌측 패널 너비 비율 (0~1) */
  splitRatio?: number;

  // ─── grouped 모드 전용 ───
  /** grouped 모드: 그룹화할 컬럼 키 */
  groupBy?: string;

  // ─── pivot 모드 전용 ───
  /** pivot 모드: row 차원 */
  pivotRows?: string[];
  /** pivot 모드: column 차원 */
  pivotColumns?: string[];
  /** pivot 모드: 값 집계 */
  pivotValues?: { column: string; aggregation: "sum" | "count" | "avg" | "min" | "max" }[];
  /**
   * pivot 모드: 풍부한 필드 정의 (PivotFieldConfig).
   * row/column/data/filter 영역 + summaryDisplayMode (10종) + groupInterval 등.
   * 단순 pivotRows/pivotColumns/pivotValues 보다 우선 사용 (있으면).
   */
  pivotFields?: PivotFieldConfig[];
  /** pivot 모드: 총합계 표시 옵션 */
  pivotTotals?: PivotTotalsConfig;
  /** pivot 모드: 시각 스타일 + 조건부 서식 */
  pivotStyle?: PivotStyleConfig;
  /** pivot 모드: 필드 선택기 */
  pivotFieldChooser?: PivotFieldChooserConfig;
  /** pivot 모드: 차트 연동 */
  pivotChart?: PivotChartConfig;
  /** pivot 모드: Excel/PDF 내보내기 */
  pivotExportConfig?: PivotExportConfig;

  // ─── card 모드 전용 ───
  /** card 모드: 한 줄에 표시할 카드 수 */
  cardsPerRow?: number;
  /** card 모드: 카드 간 간격 (px) */
  cardSpacing?: number;
  /** card 모드: 카드 시각 스타일 */
  cardStyle?: TableCardStyleConfig;
  /** card 모드: 데이터 컬럼 → 카드 영역 매핑 */
  cardColumnMapping?: TableCardColumnMapping;

  // ─── 빈 상태 / 로딩 ───
  /** 빈 상태 메시지 */
  emptyMessage?: string;

  // ─── 툴바 ───
  /** 툴바 표시 */
  showToolbar?: boolean;
  /** 엑셀 내보내기 버튼 */
  showExcel?: boolean;
  /** 새로고침 버튼 */
  showRefresh?: boolean;
}
