"use client";

/**
 * TableConnectSection — "① 테이블 연결" CPSection + CPRow "테이블" + CPSelect 공통화
 *
 * Codex 검토 (2026-04-29) 가이드:
 *  - 추출 경계 = "테이블 select + 버튼 슬롯" 에 한정
 *  - autoload 로직 (callback / 조건 / 컬럼 fetch) 은 절대 안에 넣지 말 것 (silent breakage 위험)
 *  - 호출처가 children 으로 자동 로드 버튼 + Hint 등을 직접 주입
 *
 * 사용처: search / table InvXxxConfigPanel (2 패널)
 *
 * AutoLoadButton 도 동시 export — 38줄 동일 inline 스타일 중복 제거.
 *  - autoload 로직은 onClick prop 으로만 받고, 안에 넣지 않음
 */

import React from "react";
import { Wand2 } from "lucide-react";
import { CPSection, CPRow, CPSelect } from "@/components/v2/config-panels/_shared/cp";

export interface TableConnectSectionProps {
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
  title?: string;
  desc?: string;
  rowLabel?: string;
  placeholder?: string;
  children?: React.ReactNode;
}

export const TableConnectSection: React.FC<TableConnectSectionProps> = ({
  value,
  onChange,
  options,
  title = "① 테이블 연결",
  desc,
  rowLabel = "테이블",
  placeholder = "선택...",
  children,
}) => (
  <CPSection title={title} desc={desc}>
    <CPRow label={rowLabel}>
      <CPSelect value={value} onChange={onChange}>
        <option value="">{placeholder}</option>
        {options.map((t) => (
          <option key={t.value} value={t.value}>
            {t.label}
          </option>
        ))}
      </CPSelect>
    </CPRow>
    {children}
  </CPSection>
);

export interface AutoLoadButtonProps {
  label: string;
  onClick: () => void;
  iconSize?: number;
}

export const AutoLoadButton: React.FC<AutoLoadButtonProps> = ({
  label,
  onClick,
  iconSize = 11,
}) => (
  <div style={{ marginTop: 6 }}>
    <button
      type="button"
      onClick={onClick}
      style={{
        width: "100%",
        padding: "6px 10px",
        fontSize: 10.5,
        background: "rgba(var(--v5-primary-rgb), 0.08)",
        border: "1px solid rgba(var(--v5-primary-rgb), 0.32)",
        borderRadius: 4,
        cursor: "pointer",
        color: "var(--v5-primary, #6c5ce7)",
        fontFamily: "var(--v5-font-sans)",
        fontWeight: 600,
        letterSpacing: "-0.005em",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        gap: 6,
        transition: "background .14s ease, border-color .14s ease",
      }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLButtonElement).style.background =
          "rgba(var(--v5-primary-rgb), 0.14)";
        (e.currentTarget as HTMLButtonElement).style.borderColor =
          "rgba(var(--v5-primary-rgb), 0.5)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLButtonElement).style.background =
          "rgba(var(--v5-primary-rgb), 0.08)";
        (e.currentTarget as HTMLButtonElement).style.borderColor =
          "rgba(var(--v5-primary-rgb), 0.32)";
      }}
    >
      <Wand2 size={iconSize} />
      {label}
    </button>
  </div>
);
