"use client";

/**
 * InvDataConfigPanel — "데이터 조회/선택" 카테고리 통합 ConfigPanel
 *
 * 등록 대상 (v2-* runtime id 그대로 — DB 호환):
 *  - v2-list      → 조회 (read) / 통합 목록
 *  - v2-table-list → 조회 (read) / 테이블 (legacy, hidden)
 *  - v2-repeater  → 입력 (write) / 자식 행 입력
 *
 * 마이그레이션 단계:
 *   현재 = wrapper (cp brumb + 옛 패널 위임)
 *   다음 = brumb 클릭 시 componentType 자동 전환 + 본체 점진 cp 이주 + resolver/writer
 *
 * Reference: notes/gbpark/2026-04-28-cp-panel-standard.md, 2026-04-28-invdata-inventory.md
 */

import React from "react";
import { Database, MousePointerClick, Table2, Rows3, Columns3 } from "lucide-react";
import { CPCrumb, type CPCrumbType, type CPCrumbKind } from "./_shared/cp";
import { V2ListConfigPanel } from "./V2ListConfigPanel";
import { V2TableListConfigPanel } from "./V2TableListConfigPanel";
import { InvRepeaterConfigPanel } from "./InvRepeaterConfigPanel";

type DataComponentType = "v2-list" | "v2-table-list" | "v2-repeater";
type DataKind = "read" | "write";

interface InvDataConfigPanelProps {
  config: any;
  onChange: (config: any) => void;
  /** 컴포넌트 타입 — runtime id (registerV2Components 에서 전달) */
  componentType: DataComponentType;
  /** 화면 메인 테이블명 */
  screenTableName?: string;
  /** 현재 테이블명 */
  currentTableName?: string;
  /** 테이블 컬럼 목록 */
  tableColumns?: any[];
  /** 메뉴 OBJID — 채번 규칙 등에 사용 */
  menuObjid?: number | string;
  /** 컴포넌트 타입 변경 콜백 (brumb 클릭 시) — 미구현 시 console.warn */
  onComponentTypeChange?: (next: DataComponentType) => void;
}

const KINDS: CPCrumbKind[] = [
  {
    id: "read",
    name: "조회",
    icon: <Database size={14} />,
  },
  {
    id: "write",
    name: "입력",
    icon: <MousePointerClick size={14} />,
  },
];

const TYPES_BY_KIND: Record<DataKind, CPCrumbType[]> = {
  read: [
    {
      id: "v2-list",
      name: "통합 목록",
      desc: "테이블/카드/칸반 등 다양한 표시",
      icon: <Rows3 size={14} />,
      col: "LIST",
    },
    {
      id: "v2-table-list",
      name: "테이블",
      desc: "행/열 그리드 (legacy)",
      icon: <Table2 size={14} />,
      col: "TABLE",
    },
  ],
  write: [
    {
      id: "v2-repeater",
      name: "리피터",
      desc: "자식 행 직접 입력 / 모달 선택",
      icon: <Columns3 size={14} />,
      col: "REPEATER",
    },
  ],
};

const KIND_OF_TYPE: Record<DataComponentType, DataKind> = {
  "v2-list": "read",
  "v2-table-list": "read",
  "v2-repeater": "write",
};

export const InvDataConfigPanel: React.FC<InvDataConfigPanelProps> = ({
  config,
  onChange,
  componentType,
  screenTableName,
  currentTableName,
  tableColumns,
  menuObjid,
  onComponentTypeChange,
}) => {
  const currentKind: DataKind = KIND_OF_TYPE[componentType] || "read";

  const handleKindChange = (nextKind: string) => {
    // kind 가 바뀌면 해당 kind 의 첫 type 으로 전환
    const firstType = TYPES_BY_KIND[nextKind as DataKind]?.[0]?.id as DataComponentType | undefined;
    if (!firstType || firstType === componentType) return;
    if (onComponentTypeChange) {
      onComponentTypeChange(firstType);
    } else {
      console.warn(
        "[InvDataConfigPanel] onComponentTypeChange 미구현 — kind 변경 적용 안 됨:",
        nextKind,
      );
    }
  };

  const handleTypeChange = (nextType: string) => {
    if (nextType === componentType) return;
    if (onComponentTypeChange) {
      onComponentTypeChange(nextType as DataComponentType);
    } else {
      console.warn(
        "[InvDataConfigPanel] onComponentTypeChange 미구현 — type 변경 적용 안 됨:",
        nextType,
      );
    }
  };

  return (
    <div style={{ fontFamily: "var(--v5-font-sans)", color: "var(--cp-text)" }}>
      <CPCrumb
        kinds={KINDS}
        currentKind={currentKind}
        onChangeKind={handleKindChange}
        types={TYPES_BY_KIND[currentKind] || []}
        value={componentType}
        onChange={handleTypeChange}
      />

      {/* 본체 — 현재는 옛 패널 위임. 다음 단계에서 cp 이주 */}
      {componentType === "v2-list" && (
        <V2ListConfigPanel
          config={config}
          onChange={onChange}
          currentTableName={currentTableName}
        />
      )}
      {componentType === "v2-table-list" && (
        <V2TableListConfigPanel
          config={config}
          onChange={onChange}
          screenTableName={screenTableName}
          tableColumns={tableColumns}
          menuObjid={menuObjid as number | undefined}
        />
      )}
      {componentType === "v2-repeater" && (
        <InvRepeaterConfigPanel
          config={config}
          onChange={onChange}
          screenTableName={screenTableName}
          currentTableName={currentTableName}
          tableColumns={tableColumns}
          menuObjid={menuObjid}
        />
      )}
    </div>
  );
};

export default InvDataConfigPanel;
