"use client";

import React from "react";
import { Trash2 } from "lucide-react";
import { CPSelect, CPText } from "@/components/v2/config-panels/_shared/cp";
import type { OptionFilter } from "@/lib/registry/components/input/use-option-loader";
import { ColumnPicker } from "./ColumnPicker";
import type { DbColumnOption } from "@/lib/registry/components/common/useDbColumns";

// 추가 시 fade-in keyframe (한 번만 inject)
const FILTER_ROW_KEYFRAMES = `
@keyframes filter-row-fade-in {
  from { opacity: 0; transform: translateY(-2px); }
  to   { opacity: 1; transform: translateY(0); }
}`;

function useFilterRowKeyframesOnce() {
  React.useEffect(() => {
    const id = "filter-row-keyframes";
    if (typeof document === "undefined" || document.getElementById(id)) return;
    const style = document.createElement("style");
    style.id = id;
    style.textContent = FILTER_ROW_KEYFRAMES;
    document.head.appendChild(style);
  }, []);
}

/**
 * 공용 FilterRow — Phase G.4 / G.5: 자연어 카드 형식으로 재설계.
 *
 *  ┌──────────────────────────────────────────── 🗑 ─┐
 *  │ 컬럼 [상태 (status) ▾]                          │
 *  │ 조건 [= ▾]   값 종류 [고정값 ▾]                 │
 *  │ 값   [재직                                ]   │
 *  └──────────────────────────────────────────────┘
 *
 * 각 row 가 CPSelect / CPText 로 cp 톤 일관. wrap 으로 좁아도 깔끔.
 * 사용처: stats / chart / cardList / groupedTable 의 OptionFilter 빌더.
 */

const FILTER_OP_LABELS: Array<{ value: OptionFilter["operator"]; label: string }> = [
  { value: "=", label: "같음 (=)" },
  { value: "!=", label: "같지 않음 (≠)" },
  { value: ">", label: "크다 (>)" },
  { value: "<", label: "작다 (<)" },
  { value: ">=", label: "크거나 같다 (≥)" },
  { value: "<=", label: "작거나 같다 (≤)" },
  { value: "like", label: "포함 (LIKE)" },
  { value: "in", label: "여러 값 중 하나 (IN)" },
  { value: "notIn", label: "여러 값 제외 (NOT IN)" },
  { value: "isNull", label: "값이 없음 (NULL)" },
  { value: "isNotNull", label: "값이 있음 (NOT NULL)" },
];

const VALUE_TYPE_LABELS: Array<{ value: NonNullable<OptionFilter["value_type"]>; label: string }> = [
  { value: "static", label: "고정값" },
  { value: "field", label: "폼 필드" },
  { value: "user", label: "사용자 컨텍스트" },
];

const USER_FIELD_LABELS: Array<{ value: NonNullable<OptionFilter["user_field"]>; label: string }> = [
  { value: "companyCode", label: "회사 코드" },
  { value: "userId", label: "사용자 ID" },
  { value: "deptCode", label: "부서 코드" },
  { value: "userName", label: "사용자명" },
];

export interface FilterRowProps {
  filter: OptionFilter;
  onChange: (p: Partial<OptionFilter>) => void;
  onRemove: () => void;
  /** 테이블 이름 — 있으면 컬럼 select 자동 채움 */
  tableName?: string;
  /** 외부에서 미리 받은 컬럼 (tableName 없을 때 fallback) */
  columnOptions?: DbColumnOption[];
}

export const OptionFilterRow: React.FC<FilterRowProps> = ({
  filter,
  onChange,
  onRemove,
  tableName,
  columnOptions,
}) => {
  useFilterRowKeyframesOnce();
  const valueType = filter.value_type ?? "static";
  const op = filter.operator ?? "=";
  const hideValue = op === "isNull" || op === "isNotNull";

  return (
    <div
      style={{
        position: "relative",
        border: "1px solid var(--cp-border-subtle)",
        borderRadius: 5,
        background: "var(--cp-bg-subtle)",
        padding: "8px 10px 8px 10px",
        display: "flex",
        flexDirection: "column",
        gap: 6,
        animation: "filter-row-fade-in .18s ease-out",
      }}
    >
      {/* 삭제 버튼 — 우측 상단 */}
      <button
        type="button"
        onClick={onRemove}
        title="필터 삭제"
        style={{
          position: "absolute",
          top: 6,
          right: 6,
          width: 20,
          height: 20,
          padding: 0,
          border: "none",
          background: "transparent",
          cursor: "pointer",
          color: "var(--cp-text-muted)",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          borderRadius: 4,
          transition: "color .15s ease, background-color .15s ease",
        }}
        onMouseEnter={(e) => {
          const b = e.currentTarget as HTMLButtonElement;
          b.style.color = "hsl(var(--destructive))";
          b.style.background = "hsl(var(--destructive) / 0.10)";
        }}
        onMouseLeave={(e) => {
          const b = e.currentTarget as HTMLButtonElement;
          b.style.color = "var(--cp-text-muted)";
          b.style.background = "transparent";
        }}
      >
        <Trash2 size={12} />
      </button>

      {/* row 1: 컬럼 */}
      <FieldRow label="컬럼">
        <ColumnPicker
          tableName={tableName}
          columnOptions={columnOptions}
          value={filter.column}
          onChange={(v) => onChange({ column: v ?? "" })}
          placeholder="컬럼 선택…"
        />
      </FieldRow>

      {/* row 2: 조건 + (필요시) 값 종류 */}
      <FieldRow label="조건">
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <div style={{ flex: "1 1 140px", minWidth: 120 }}>
            <CPSelect
              value={op}
              onChange={(v) => onChange({ operator: v as OptionFilter["operator"] })}
            >
              {FILTER_OP_LABELS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </CPSelect>
          </div>
          {!hideValue && (
            <div style={{ flex: "1 1 120px", minWidth: 100 }}>
              <CPSelect
                value={valueType}
                onChange={(v) =>
                  onChange({
                    value_type: v as OptionFilter["value_type"],
                    value: v === "static" ? filter.value : undefined,
                    field_ref: v === "field" ? filter.field_ref : undefined,
                    user_field: v === "user" ? filter.user_field : undefined,
                  })
                }
              >
                {VALUE_TYPE_LABELS.map((o) => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </CPSelect>
            </div>
          )}
        </div>
      </FieldRow>

      {/* row 3: 값 (hideValue 면 안 보임) */}
      {!hideValue && (
        <FieldRow label="값">
          {valueType === "static" ? (
            <CPText
              value={(filter.value as string | undefined) ?? ""}
              onChange={(v) => onChange({ value: v })}
              placeholder={
                op === "in" || op === "notIn"
                  ? "쉼표로 구분 — 예: 재직, 휴직, 퇴사"
                  : "고정값 입력 — 예: 재직"
              }
            />
          ) : valueType === "field" ? (
            <CPText
              value={filter.field_ref ?? ""}
              onChange={(v) => onChange({ field_ref: v })}
              placeholder="폼 필드명 — 화면의 어떤 입력값을 따라갈지"
            />
          ) : (
            <CPSelect
              value={filter.user_field ?? "companyCode"}
              onChange={(v) => onChange({ user_field: v as OptionFilter["user_field"] })}
            >
              {USER_FIELD_LABELS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </CPSelect>
          )}
        </FieldRow>
      )}
    </div>
  );
};

// ───────────────────────────────────────────────────────
// FieldRow — 라벨 + 값 한 줄 (cp Row 톤, label 폭 고정)
// ───────────────────────────────────────────────────────
function FieldRow({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "40px minmax(0, 1fr)",
        alignItems: "center",
        columnGap: 8,
        minWidth: 0,
      }}
    >
      <span
        style={{
          fontSize: 10.5,
          fontWeight: 700,
          color: "var(--cp-text-sec)",
          letterSpacing: "-0.005em",
        }}
      >
        {label}
      </span>
      <div style={{ minWidth: 0 }}>{children}</div>
    </div>
  );
}
