"use client";

import { PopComponentRegistry } from "../../PopComponentRegistry";
import { PopFieldComponent } from "./PopFieldComponent";
import { PopFieldConfigPanel } from "./PopFieldConfig";
import type { PopFieldConfig } from "./types";
import { DEFAULT_FIELD_CONFIG, FIELD_INPUT_TYPE_LABELS } from "./types";

function PopFieldPreviewComponent({
  config,
  label,
}: {
  config?: PopFieldConfig;
  label?: string;
}) {
  const cfg: PopFieldConfig = {
    ...DEFAULT_FIELD_CONFIG,
    ...config,
    sections: config?.sections?.length ? config.sections : DEFAULT_FIELD_CONFIG.sections,
  };
  const totalFields = cfg.sections.reduce(
    (sum, s) => sum + (s.fields?.length || 0),
    0
  );
  const sectionCount = cfg.sections.length;

  return (
    <div className="flex h-full w-full flex-col items-center justify-center gap-1 p-2">
      <span className="text-[10px] font-medium text-muted-foreground">
        {label || "입력 필드"}
      </span>
      <div className="flex flex-wrap gap-1">
        {cfg.sections.map((section) =>
          (section.fields || []).slice(0, 3).map((field) => (
            <div
              key={field.id}
              className="flex h-5 items-center rounded border border-dashed border-muted-foreground/30 px-1.5"
            >
              <span className="text-[8px] text-muted-foreground">
                {field.labelText || field.fieldName || FIELD_INPUT_TYPE_LABELS[field.inputType]}
              </span>
            </div>
          ))
        )}
      </div>
      <span className="text-[8px] text-muted-foreground">
        {sectionCount}섹션 / {totalFields}필드
      </span>
    </div>
  );
}

PopComponentRegistry.registerComponent({
  id: "pop-field",
  name: "입력 필드",
  description: "저장용 값 입력 (섹션별 멀티필드, 읽기전용/입력 혼합)",
  category: "input",
  icon: "TextCursorInput",
  component: PopFieldComponent,
  configPanel: PopFieldConfigPanel,
  preview: PopFieldPreviewComponent,
  defaultProps: DEFAULT_FIELD_CONFIG,
  connectionMeta: {
    sendable: [
      {
        key: "value_changed",
        label: "값 변경",
        type: "value",
        category: "data",
        description: "필드값 변경 시 fieldName + value + allValues 전달",
      },
      {
        key: "collected_data",
        label: "수집 응답",
        type: "event",
        category: "event",
        description: "데이터 수집 요청에 대한 응답 (입력값 + 매핑)",
      },
    ],
    receivable: [
      {
        key: "set_value",
        label: "값 설정",
        type: "value",
        category: "data",
        description: "외부에서 특정 필드 또는 일괄로 값 세팅",
      },
      {
        key: "collect_data",
        label: "수집 요청",
        type: "event",
        category: "event",
        description: "버튼에서 데이터+매핑 수집 요청 수신",
      },
    ],
  },
  touchOptimized: true,
  supportedDevices: ["mobile", "tablet"],
});
