"use client";

/**
 * UnifiedList 설정 패널
 * TableListConfigPanel을 래핑하여 동일한 설정 기능을 제공합니다.
 * 카드 표시는 별도의 card-display 컴포넌트를 사용합니다.
 */

import React, { useMemo } from "react";
import { TableListConfigPanel } from "@/lib/registry/components/table-list/TableListConfigPanel";
import { TableListConfig } from "@/lib/registry/components/table-list/types";

interface UnifiedListConfigPanelProps {
  config: Record<string, any>;
  onChange: (config: Record<string, any>) => void;
  /** 현재 화면의 테이블명 */
  currentTableName?: string;
}

/**
 * UnifiedList 설정 패널
 * TableListConfigPanel과 동일한 기능을 제공
 */
export const UnifiedListConfigPanel: React.FC<UnifiedListConfigPanelProps> = ({
  config,
  onChange,
  currentTableName,
}) => {
  // UnifiedList config를 TableListConfig 형식으로 변환
  const tableListConfig: TableListConfig = useMemo(() => {
    // 컬럼 형식 변환: UnifiedList columns -> TableList columns
    const columns = (config.columns || []).map((col: any, index: number) => ({
      columnName: col.key || col.columnName || col.field || "",
      displayName: col.title || col.header || col.displayName || col.key || col.columnName || col.field || "",
      width: col.width ? parseInt(col.width, 10) : undefined,
      visible: col.visible !== false,
      sortable: col.sortable !== false,
      searchable: col.searchable !== false,
      align: col.align || "left",
      order: index,
      isEntityJoin: col.isJoinColumn || col.isEntityJoin || false,
      thousandSeparator: col.thousandSeparator,
      editable: col.editable,
      entityDisplayConfig: col.entityDisplayConfig,
    }));

    return {
      selectedTable: config.tableName || config.dataSource?.table || currentTableName,
      tableName: config.tableName || config.dataSource?.table || currentTableName,
      columns,
      useCustomTable: config.useCustomTable,
      customTableName: config.customTableName,
      isReadOnly: config.isReadOnly !== false, // UnifiedList는 기본적으로 읽기 전용
      displayMode: "table", // 테이블 모드 고정 (카드는 card-display 컴포넌트 사용)
      pagination: config.pagination !== false ? {
        enabled: true,
        pageSize: config.pageSize || 10,
        position: "bottom",
        showPageSize: true,
        pageSizeOptions: [5, 10, 20, 50, 100],
      } : {
        enabled: false,
        pageSize: 10,
        position: "bottom",
        showPageSize: false,
        pageSizeOptions: [10],
      },
      filter: config.filter,
      dataFilter: config.dataFilter,
      checkbox: {
        enabled: true,
        position: "left",
        showHeader: true,
      },
      height: "auto",
      autoWidth: true,
      stickyHeader: true,
      autoLoad: true,
      horizontalScroll: {
        enabled: true,
        minColumnWidth: 100,
        maxColumnWidth: 300,
      },
    };
  }, [config, currentTableName]);

  // TableListConfig 변경을 UnifiedList config 형식으로 변환
  const handleConfigChange = (partialConfig: Partial<TableListConfig>) => {
    const newConfig: Record<string, any> = { ...config };

    // 테이블 설정 변환
    if (partialConfig.selectedTable !== undefined) {
      newConfig.tableName = partialConfig.selectedTable;
      if (!newConfig.dataSource) {
        newConfig.dataSource = {};
      }
      newConfig.dataSource.table = partialConfig.selectedTable;
    }
    if (partialConfig.tableName !== undefined) {
      newConfig.tableName = partialConfig.tableName;
      if (!newConfig.dataSource) {
        newConfig.dataSource = {};
      }
      newConfig.dataSource.table = partialConfig.tableName;
    }
    if (partialConfig.useCustomTable !== undefined) {
      newConfig.useCustomTable = partialConfig.useCustomTable;
      }
    if (partialConfig.customTableName !== undefined) {
      newConfig.customTableName = partialConfig.customTableName;
    }
    if (partialConfig.isReadOnly !== undefined) {
      newConfig.isReadOnly = partialConfig.isReadOnly;
    }

    // 컬럼 형식 변환: TableList columns -> UnifiedList columns
    if (partialConfig.columns !== undefined) {
      newConfig.columns = partialConfig.columns.map((col: any) => ({
        key: col.columnName,
        field: col.columnName,
        title: col.displayName,
        header: col.displayName,
        width: col.width ? String(col.width) : undefined,
        visible: col.visible,
        sortable: col.sortable,
        searchable: col.searchable,
        align: col.align,
        isJoinColumn: col.isEntityJoin,
        isEntityJoin: col.isEntityJoin,
        thousandSeparator: col.thousandSeparator,
        editable: col.editable,
        entityDisplayConfig: col.entityDisplayConfig,
      }));
    }

    // 페이지네이션 변환
    if (partialConfig.pagination !== undefined) {
      newConfig.pagination = partialConfig.pagination?.enabled;
      newConfig.pageSize = partialConfig.pagination?.pageSize || 10;
    }

    // 필터 변환
    if (partialConfig.filter !== undefined) {
      newConfig.filter = partialConfig.filter;
    }

    // 데이터 필터 변환
    if (partialConfig.dataFilter !== undefined) {
      newConfig.dataFilter = partialConfig.dataFilter;
    }

    console.log("⚙️ UnifiedListConfigPanel handleConfigChange:", { partialConfig, newConfig });
    onChange(newConfig);
  };

  return (
    <TableListConfigPanel
      config={tableListConfig}
      onChange={handleConfigChange}
      screenTableName={currentTableName}
    />
  );
};

UnifiedListConfigPanel.displayName = "UnifiedListConfigPanel";

export default UnifiedListConfigPanel;
