"use client";

/**
 * FieldsPanel — 화면 수준 FieldConfig[] 편집 패널
 *
 * ScreenDesigner 의 좌측 통합 패널에 "필드" 탭으로 들어간다. 현재 선택된 화면의
 * primary table 을 기준으로 백엔드 메타 API (/api/meta/tables/{name}/fields) 를
 * 호출해 FieldConfig[] 를 받아오고, 필드별 visible / searchable 등을 편집할 수
 * 있다. 편집 결과는 onFieldsChange 로 상위에 올라가 ScreenDefinition.fields 에
 * 저장된다.
 *
 * 역할:
 *   - 테이블 메타 읽기 (Phase 1 API 활용)
 *   - 필드 목록 표시 (PK / 필수 / 시스템 필드 구분 배지)
 *   - 필드별 visible / searchable 토글
 *   - 순서 재정렬 (위/아래 버튼)
 *
 * 범위 밖:
 *   - 고급 편집(label, options, ref, computed 등)은 추후 확장
 *   - 필드 추가/삭제는 DB 메타 소스 기준이므로 지원 안 함
 */

import React, { useEffect, useMemo, useState } from "react";
import { getMetaFields } from "@/lib/api/meta";
import type { FieldConfig } from "@/types/invyone-component";

interface FieldsPanelProps {
  /** 현재 선택된 화면의 primary table 이름 */
  tableName: string | null | undefined;
  /** 현재 ScreenDefinition.fields 값 */
  fields?: FieldConfig[];
  /** 편집 결과를 상위에 반영하는 콜백 */
  onFieldsChange: (next: FieldConfig[]) => void;
}

export function FieldsPanel({
  tableName,
  fields,
  onFieldsChange,
}: FieldsPanelProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 현재 편집 중인 필드 목록. prop 이 바뀌면 재동기화.
  const localFields = useMemo<FieldConfig[]>(() => fields ?? [], [fields]);

  // 테이블이 바뀌고 fields 가 비어 있으면 자동 로드 (편의성)
  useEffect(() => {
    if (!tableName) return;
    if (localFields.length > 0) return;
    void handleLoad();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tableName]);

  const handleLoad = async () => {
    if (!tableName) {
      setError("테이블이 선택되지 않았습니다");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await getMetaFields(tableName);
      const loaded = (data?.fields ?? []) as FieldConfig[];
      onFieldsChange(loaded);
    } catch (err: any) {
      setError(err?.message ?? "필드 로드 실패");
    } finally {
      setLoading(false);
    }
  };

  const patch = (column: string, patchObj: Partial<FieldConfig>) => {
    const next = localFields.map((f) =>
      f.column === column ? { ...f, ...patchObj } : f,
    );
    onFieldsChange(next);
  };

  const toggleVisible = (column: string) => {
    const target = localFields.find((f) => f.column === column);
    if (!target) return;
    patch(column, { visible: !(target.visible !== false) });
  };

  const toggleSearchable = (column: string) => {
    const target = localFields.find((f) => f.column === column);
    if (!target) return;
    patch(column, { searchable: !target.searchable });
  };

  const move = (column: string, delta: -1 | 1) => {
    const idx = localFields.findIndex((f) => f.column === column);
    if (idx < 0) return;
    const target = idx + delta;
    if (target < 0 || target >= localFields.length) return;
    const next = [...localFields];
    [next[idx], next[target]] = [next[target], next[idx]];
    // order 재부여
    next.forEach((f, i) => {
      f.order = i + 1;
    });
    onFieldsChange(next);
  };

  const visibleCount = localFields.filter((f) => f.visible !== false).length;
  const searchableCount = localFields.filter((f) => f.searchable).length;

  return (
    <div className="flex h-full flex-col overflow-hidden">
      {/* 헤더 — 테이블명 + 로드 버튼 */}
      <div className="border-border flex items-center gap-2 border-b px-3 py-2">
        <div className="text-muted-foreground min-w-0 flex-1 truncate font-mono text-xs">
          {tableName ? tableName : <span className="italic">테이블 없음</span>}
        </div>
        <button
          type="button"
          onClick={handleLoad}
          disabled={!tableName || loading}
          className="border-border text-foreground hover:bg-accent disabled:opacity-40 rounded border px-2 py-0.5 text-xs transition-colors"
        >
          {loading ? "로딩…" : "메타에서 로드"}
        </button>
      </div>

      {/* 에러 */}
      {error && (
        <div className="border-destructive/40 bg-destructive/10 text-destructive border-b px-3 py-1.5 text-xs">
          ⚠ {error}
        </div>
      )}

      {/* 필드 목록 */}
      {localFields.length === 0 ? (
        <div className="text-muted-foreground flex flex-1 items-center justify-center px-4 text-center text-xs leading-relaxed">
          {tableName ? (
            <>
              필드가 없습니다.
              <br />
              &ldquo;메타에서 로드&rdquo; 를 눌러 자동 생성하세요.
            </>
          ) : (
            <>
              화면에 테이블을 지정한 뒤
              <br />
              이 패널에서 필드를 관리합니다.
            </>
          )}
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto">
          {localFields.map((f, idx) => (
            <div
              key={f.column}
              className="border-border hover:bg-accent/50 group flex items-center gap-1.5 border-b px-2 py-1.5"
            >
              {/* visible 체크 */}
              <button
                type="button"
                onClick={() => toggleVisible(f.column)}
                className={`flex size-4 shrink-0 items-center justify-center rounded border text-[0.55rem] ${
                  f.visible !== false
                    ? "bg-primary text-primary-foreground border-primary"
                    : "border-border text-transparent"
                }`}
                title={f.visible !== false ? "숨기기" : "표시"}
              >
                ✓
              </button>

              {/* 라벨 + 컬럼명 */}
              <div className="min-w-0 flex-1">
                <div className="text-foreground truncate text-xs font-medium">
                  {f.label}
                </div>
                <div className="text-muted-foreground truncate font-mono text-[0.55rem]">
                  {f.column}
                </div>
              </div>

              {/* 타입 배지 */}
              <span className="bg-muted text-muted-foreground shrink-0 rounded px-1 py-0.5 text-[0.55rem]">
                {f.type}
              </span>

              {/* PK / 필수 / 시스템 배지 */}
              {f.pk && (
                <span
                  className="bg-primary text-primary-foreground shrink-0 rounded px-1 py-0.5 text-[0.55rem] font-bold"
                  title="Primary Key"
                >
                  PK
                </span>
              )}
              {f.required && !f.pk && (
                <span
                  className="bg-destructive text-destructive-foreground shrink-0 rounded px-1 py-0.5 text-[0.55rem] font-bold"
                  title="필수"
                >
                  *
                </span>
              )}
              {f.system && (
                <span
                  className="text-muted-foreground bg-muted shrink-0 rounded px-1 py-0.5 text-[0.55rem]"
                  title="시스템 필드"
                >
                  sys
                </span>
              )}

              {/* searchable 토글 */}
              <button
                type="button"
                onClick={() => toggleSearchable(f.column)}
                className={`shrink-0 rounded px-1 py-0.5 text-[0.55rem] font-bold transition-colors ${
                  f.searchable
                    ? "bg-primary/20 text-primary"
                    : "text-muted-foreground/50 hover:text-muted-foreground"
                }`}
                title="검색 대상"
              >
                🔍
              </button>

              {/* 순서 이동 */}
              <div className="flex shrink-0 flex-col opacity-0 transition-opacity group-hover:opacity-100">
                <button
                  type="button"
                  onClick={() => move(f.column, -1)}
                  disabled={idx === 0}
                  className="text-muted-foreground hover:text-foreground disabled:opacity-20 text-[0.5rem] leading-none"
                  title="위로"
                >
                  ▲
                </button>
                <button
                  type="button"
                  onClick={() => move(f.column, 1)}
                  disabled={idx === localFields.length - 1}
                  className="text-muted-foreground hover:text-foreground disabled:opacity-20 text-[0.5rem] leading-none"
                  title="아래로"
                >
                  ▼
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 상태바 */}
      <div className="border-border text-muted-foreground flex items-center justify-between border-t px-3 py-1.5 text-[0.55rem]">
        <span>
          총 <b className="text-foreground">{localFields.length}</b> 필드
        </span>
        <span>
          표시 <b className="text-foreground">{visibleCount}</b> · 검색{" "}
          <b className="text-foreground">{searchableCount}</b>
        </span>
      </div>
    </div>
  );
}

export default FieldsPanel;
