export interface ReportTemplate {
  template_id: string;
  template_name_kor: string;
  template_name_eng: string | null;
  template_type: string;
  is_system: string;
  thumbnail_url: string | null;
  description: string | null;
  layout_config: string | null;
  default_queries: string | null;
  use_yn: string;
  sort_order: number;
  created_at: string;
  created_by: string | null;
  updated_at: string | null;
  updated_by: string | null;
}

export interface ReportMaster {
  report_id: string;
  report_name_kor: string;
  report_name_eng: string | null;
  template_id: string | null;
  template_name: string | null;
  report_type: string;
  company_code: string | null;
  description: string | null;
  use_yn: string;
  created_at: string;
  created_by: string | null;
  updated_at: string | null;
  updated_by: string | null;
}

export interface ReportLayout {
  layout_id: string;
  report_id: string;
  canvas_width: number;
  canvas_height: number;
  page_orientation: string;
  margin_top: number;
  margin_bottom: number;
  margin_left: number;
  margin_right: number;
  components: ComponentConfig[];
  pages?: ReportPage[];
  created_at: string;
  created_by: string | null;
  updated_at: string | null;
  updated_by: string | null;
}

export interface ReportQuery {
  query_id: string;
  report_id: string;
  query_name: string;
  query_type: "MASTER" | "DETAIL";
  sql_query: string;
  parameters: string[];
  external_connection_id: number | null;
  display_order: number;
  created_at: string;
  created_by: string | null;
  updated_at: string | null;
  updated_by: string | null;
}

export interface ExternalConnection {
  id: number;
  connection_name: string;
  db_type: string;
  description?: string;
  is_active: string;
}

export interface WatermarkConfig {
  enabled: boolean;
  type: "text" | "image";
  text?: string;
  fontSize?: number;
  fontColor?: string;
  imageUrl?: string;
  opacity: number;
  style: "diagonal" | "center" | "tile";
  rotation?: number;
}

export interface ReportPage {
  page_id: string;
  page_name: string;
  page_order: number;
  width: number;
  height: number;
  orientation: "portrait" | "landscape";
  margins: {
    top: number;
    bottom: number;
    left: number;
    right: number;
  };
  background_color: string;
  components: ComponentConfig[];
}

export interface ReportLayoutConfig {
  pages: ReportPage[];
  watermark?: WatermarkConfig;
}

export interface ComponentConfig {
  id: string;
  type: string;
  x: number;
  y: number;
  width: number;
  height: number;
  zIndex: number;
  fontSize?: number;
  fontFamily?: string;
  fontWeight?: string;
  fontColor?: string;
  backgroundColor?: string;
  borderWidth?: number;
  borderColor?: string;
  borderRadius?: number;
  textAlign?: string;
  verticalAlign?: "top" | "middle" | "bottom";
  padding?: number;
  lineHeight?: number;
  letterSpacing?: number;
  textDecoration?: "none" | "underline" | "line-through";
  fontStyle?: "normal" | "italic";
  textTransform?: "none" | "uppercase" | "lowercase";
  textOverflow?: "clip" | "ellipsis" | "wrap";
  textPreset?: string;
  queryId?: string;
  fieldName?: string;
  defaultValue?: string;
  format?: string;
  visible?: boolean;
  printable?: boolean;
  conditional?: string;
  conditionalRule?: ConditionalRule;
  conditionalRules?: ConditionalRule[];
  gridConditionalRule?: ConditionalRule;
  gridConditionalRules?: ConditionalRule[];
  locked?: boolean;
  groupId?: string;
  imageUrl?: string;
  imageFile?: File;
  objectFit?: "contain" | "cover" | "fill" | "none";
  imageOpacity?: number;
  imageBorderRadius?: number;
  imageCaption?: string;
  imageCaptionPosition?: "top" | "bottom";
  imageCaptionFontSize?: number;
  imageCaptionColor?: string;
  imageCaptionAlign?: "left" | "center" | "right";
  imageAlt?: string;
  imageRotation?: number;
  imageFlipH?: boolean;
  imageFlipV?: boolean;
  imageCropX?: number;
  imageCropY?: number;
  imageCropWidth?: number;
  imageCropHeight?: number;
  orientation?: "horizontal" | "vertical";
  lineStyle?: "solid" | "dashed" | "dotted" | "double";
  lineWidth?: number;
  lineColor?: string;
  showLabel?: boolean;
  labelText?: string;
  labelPosition?: "top" | "left" | "bottom" | "right";
  personName?: string;
  tableColumns?: Array<{
    field: string;
    header: string;
    width?: number;
    align?: "left" | "center" | "right";
    mappingType?: "field" | "formula";
    formula?: string;
    summaryType?: "SUM" | "AVG" | "COUNT" | "NONE";
    /** 컬럼 표시 여부 — false일 때 렌더링에서 제외 (기본: true) */
    visible?: boolean;
    /** 숫자 포맷 — "none" | "comma" | "currency" (기본: "none") */
    numberFormat?: "none" | "comma" | "currency";
    /** 통화 단위 (numberFormat="currency"일 때, 기본: "원") */
    currencySuffix?: string;
  }>;
  showFooter?: boolean;
  exportSummaryId?: string;
  headerBackgroundColor?: string;
  headerTextColor?: string;
  showBorder?: boolean;
  rowHeight?: number;
  pageNumberFormat?: "number" | "numberTotal" | "koreanNumber";
  cardTitle?: string;
  cardItems?: Array<{
    label: string;
    value: string;
    fieldName?: string;
  }>;
  labelWidth?: number;
  showCardBorder?: boolean;
  showCardTitle?: boolean;
  titleFontSize?: number;
  labelFontSize?: number;
  valueFontSize?: number;
  titleColor?: string;
  labelColor?: string;
  valueColor?: string;
  calcItems?: Array<{
    label: string;
    value: number | string;
    operator: "+" | "-" | "x" | "÷";
    fieldName?: string;
  }>;
  resultLabel?: string;
  resultColor?: string;
  resultFontSize?: number;
  showCalcBorder?: boolean;
  numberFormat?: "none" | "comma" | "currency";
  currencySuffix?: string;
  barcodeType?: "CODE128" | "CODE39" | "EAN13" | "EAN8" | "UPC" | "QR";
  barcodeValue?: string;
  barcodeFieldName?: string;
  showBarcodeText?: boolean;
  barcodeColor?: string;
  barcodeBackground?: string;
  barcodeMargin?: number;
  qrErrorCorrectionLevel?: "L" | "M" | "Q" | "H";
  qrDataFields?: Array<{
    fieldName: string;
    label: string;
  }>;
  qrUseMultiField?: boolean;
  qrIncludeAllRows?: boolean;
  checkboxChecked?: boolean;
  checkboxFieldName?: string;
  checkboxLabel?: string;
  checkboxSize?: number;
  checkboxColor?: string;
  checkboxBorderColor?: string;
  checkboxLabelPosition?: "left" | "right";
  chartQueryId?: string;
  chartLabelField?: string;
  chartValueField?: string;
  chartColors?: string[];
  chartInnerRadius?: number;
  chartShowLegend?: boolean;
  chartTitle?: string;
  /** 테이블 컴포넌트의 데이터 소스 테이블/뷰명 */
  dataTableName?: string;
  /** 테이블 모드에서 미리보기 행 수 */
  tableRowCount?: number;
  content?: string;
  text?: string;
  conditionalStyles?: Array<{ value: string; backgroundColor?: string; fontColor?: string }>;
  // 비주얼 쿼리 빌더 (table 컴포넌트 전용)
  visualQuery?: VisualQuery;
  visualDataSource?: VisualDataSource;
  // 카드 레이아웃 설정 (card 컴포넌트 전용 - v3)
  cardLayoutConfig?: CardLayoutConfig;

  // 그리드 양식 모드 (table 컴포넌트 전용)
  gridMode?: boolean;
  gridCells?: GridCell[];
  gridRowCount?: number;
  gridColCount?: number;
  gridColWidths?: number[];
  gridRowHeights?: number[];
  gridHeaderRows?: number;
  gridHeaderCols?: number;
  /** 격자 모드 하단 요약(푸터) 행 수 */
  gridFooterRows?: number;
  /** 격자 모드 푸터 표시 여부 */
  gridShowFooter?: boolean;
}

export interface ReportDetail {
  report: ReportMaster;
  layout: ReportLayout | null;
  queries: ReportQuery[];
  menuObjids?: number[];
}

export interface GetReportsResponse {
  items: ReportMaster[];
  total: number;
  page: number;
  limit: number;
  typeSummary: Array<{ type: string; count: number }>;
  allTypes: string[];
  recentActivity: Array<{ date: string; count: number }>;
  recentTotal: number;
}

export interface GetReportsParams {
  page?: number;
  limit?: number;
  searchText?: string;
  searchField?: "report_name" | "created_by" | "report_type" | "updated_at" | "created_at";
  startDate?: string;
  endDate?: string;
  reportType?: string;
  useYn?: string;
  sortBy?: string;
  sortOrder?: "ASC" | "DESC";
}

export interface CreateReportRequest {
  reportNameKor: string;
  reportNameEng?: string;
  templateId?: string;
  reportType: string;
  description?: string;
  companyCode?: string;
}

export interface UpdateReportRequest {
  reportNameKor?: string;
  reportNameEng?: string;
  reportType?: string;
  description?: string;
  useYn?: string;
}

export interface SaveLayoutRequest {
  layoutConfig: ReportLayoutConfig;
  queries?: Array<{
    id: string;
    name: string;
    type: "MASTER" | "DETAIL";
    sqlQuery: string;
    parameters: string[];
    externalConnectionId?: number;
  }>;
  menuObjids?: number[];
}

export interface GetTemplatesResponse {
  system: ReportTemplate[];
  custom: ReportTemplate[];
}

export interface CreateTemplateRequest {
  templateNameKor: string;
  templateNameEng?: string;
  templateType: string;
  description?: string;
  layoutConfig?: Record<string, unknown>;
  defaultQueries?: Array<Record<string, unknown>>;
}

export interface GetReportsByMenuResponse {
  items: ReportMaster[];
  total: number;
}

export interface ConditionalRule {
  queryId: string;
  field: string;
  operator: "eq" | "ne" | "gt" | "lt" | "gte" | "lte" | "contains" | "notEmpty" | "empty";
  value: string;
  action: "show" | "hide";
}

export interface VisualQueryFormulaColumn {
  alias: string;
  header: string;
  expression: string;
}

export interface VisualQuery {
  tableName: string;
  limit?: number;
  columns: string[];
  formulaColumns: VisualQueryFormulaColumn[];
}

// ─────────────────────────────────────────────────────────────────────────────
// 그리드 양식 셀 타입 정의 (복잡한 테이블 — 셀 병합, 고정텍스트/데이터 혼합)
// ─────────────────────────────────────────────────────────────────────────────

export interface GridCell {
  id: string;
  row: number;
  col: number;
  rowSpan?: number;
  colSpan?: number;
  cellType: "static" | "field" | "formula" | "input";
  value?: string;
  field?: string;
  formula?: string;
  /** input 셀의 placeholder 힌트 */
  inputPlaceholder?: string;
  align?: "left" | "center" | "right";
  verticalAlign?: "top" | "middle" | "bottom";
  fontWeight?: "normal" | "bold";
  fontSize?: number;
  backgroundColor?: string;
  textColor?: string;
  borderStyle?: "thin" | "medium" | "thick" | "none";
  numberFormat?: "none" | "comma" | "currency";
  currencySuffix?: string;
  merged?: boolean;
  mergedBy?: string;
  /** 셀 요약(집계) 유형 — 격자 모드에서 푸터 행 셀에 적용 */
  summaryType?: "SUM" | "AVG" | "COUNT" | "NONE";
}

// ─────────────────────────────────────────────────────────────────────────────
// 카드 레이아웃 v3 타입 정의
// ─────────────────────────────────────────────────────────────────────────────

/** 카드 내부 요소 타입 */
export type CardElementType =
  | "header" | "dataCell" | "divider" | "badge"
  | "image" | "number" | "date" | "link" | "status" | "spacer" | "staticText";

/** 데이터 셀 방향 */
export type CellDirection = "vertical" | "horizontal";

/** 카드 요소 공통 인터페이스 */
export interface CardElementBase {
  id: string;
  type: CardElementType;
  colspan?: number;
  rowspan?: number;
  direction?: CellDirection;
}

/** 헤더 요소 */
export interface CardHeaderElement extends CardElementBase {
  type: "header";
  icon?: string;
  iconColor?: string;
  title: string;
  titleColor?: string;
  titleFontSize?: number;
  fontSize?: number;
  color?: string;
  fontWeight?: string;
}

/** 데이터 셀 요소 */
export interface CardDataCellElement extends CardElementBase {
  type: "dataCell";
  direction: CellDirection;
  label: string;
  columnName?: string;
  inputType?: "text" | "date" | "number" | "select" | "readonly";
  required?: boolean;
  placeholder?: string;
  selectOptions?: string[];
  labelWidth?: number;
  labelFontSize?: number;
  labelColor?: string;
  valueFontSize?: number;
  valueColor?: string;
  labelFontWeight?: string;
}

/** 구분선 요소 */
export interface CardDividerElement extends CardElementBase {
  type: "divider";
  style?: "solid" | "dashed" | "dotted";
  color?: string;
  thickness?: number;
}

/** 뱃지 요소 */
export interface CardBadgeElement extends CardElementBase {
  type: "badge";
  label?: string;
  columnName?: string;
  colorMap?: Record<string, string>;
  bgColor?: string;
  textColor?: string;
}

/** 이미지 요소 */
export interface CardImageElement extends CardElementBase {
  type: "image";
  columnName?: string;
  altText?: string;
  objectFit?: "contain" | "cover" | "fill";
  height?: number;
}

/** 숫자/금액 요소 */
export interface CardNumberElement extends CardElementBase {
  type: "number";
  label: string;
  columnName?: string;
  numberFormat?: "none" | "comma" | "currency";
  currencySuffix?: string;
  labelFontSize?: number;
  labelColor?: string;
  valueFontSize?: number;
  valueColor?: string;
}

/** 날짜 요소 */
export interface CardDateElement extends CardElementBase {
  type: "date";
  label: string;
  columnName?: string;
  dateFormat?: string;
  labelFontSize?: number;
  labelColor?: string;
  valueFontSize?: number;
  valueColor?: string;
}

/** 링크 요소 */
export interface CardLinkElement extends CardElementBase {
  type: "link";
  label: string;
  columnName?: string;
  linkText?: string;
  openInNewTab?: boolean;
}

/** 상태 요소 */
export interface CardStatusElement extends CardElementBase {
  type: "status";
  columnName?: string;
  statusMappings?: Array<{ value: string; label: string; color: string }>;
}

/** 빈 공간 요소 */
export interface CardSpacerElement extends CardElementBase {
  type: "spacer";
  height?: number;
}

/** 고정 텍스트 요소 */
export interface CardStaticTextElement extends CardElementBase {
  type: "staticText";
  text: string;
  fontSize?: number;
  color?: string;
  fontWeight?: "normal" | "bold";
  textAlign?: "left" | "center" | "right";
}

/** 통합 요소 타입 */
export type CardElement =
  | CardHeaderElement
  | CardDataCellElement
  | CardDividerElement
  | CardBadgeElement
  | CardImageElement
  | CardNumberElement
  | CardDateElement
  | CardLinkElement
  | CardStatusElement
  | CardSpacerElement
  | CardStaticTextElement;

/** 카드 행 정의 */
export interface CardLayoutRow {
  id: string;
  gridColumns: number;
  elements: CardElement[];
  height?: string;
  gap?: string;
  marginBottom?: string;
}

/** 카드 레이아웃 전체 설정 */
export interface CardLayoutConfig {
  tableName?: string;
  primaryKey?: string;
  rows: CardLayoutRow[];
  padding?: string;
  gap?: string;
  borderStyle?: string;
  borderColor?: string;
  backgroundColor?: string;
  headerTitleFontSize?: number;
  headerTitleColor?: string;
  labelFontSize?: number;
  labelColor?: string;
  valueFontSize?: number;
  valueColor?: string;
  dividerThickness?: number;
  dividerColor?: string;
  accentBorderColor?: string;
  accentBorderWidth?: number;
  borderRadius?: string;
  borderWidth?: number;
  headerFontWeight?: "normal" | "bold";
  valueFontWeight?: "normal" | "bold";
}

// ─────────────────────────────────────────────────────────────────────────────
// 그리드 설정
// ─────────────────────────────────────────────────────────────────────────────

export interface GridConfig {
  visible: boolean;
  snapToGrid: boolean;
  cellWidth: number;
  cellHeight: number;
  columns: number;
  rows: number;
  gridColor: string;
  gridOpacity: number;
}

// ─────────────────────────────────────────────────────────────────────────────
// 비주얼 데이터 소스 (마스터-디테일 구조)
// ─────────────────────────────────────────────────────────────────────────────

export interface VisualColumn {
  name: string;
  label?: string;
  dataType?: string;
  selected?: boolean;
}

export interface JoinKeyPair {
  masterColumn: string;
  detailColumn: string;
  autoDetected?: boolean;
}

export interface VisualDetailSource {
  id: string;
  tableName: string;
  columns: VisualColumn[];
  joinKeys: JoinKeyPair[];
}

export interface VisualDataSource {
  master: { tableName: string; columns: VisualColumn[] };
  details: VisualDetailSource[];
}
