"use client";

import React, { useMemo } from "react";
import { X, Type, Settings2, Tag, ToggleLeft, ChevronDown, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Badge } from "@/components/ui/badge";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import type { ColumnTypeInfo, TableInfo, SecondLevelMenu } from "./types";
import { INPUT_TYPE_COLORS } from "./types";
import type { ReferenceTableColumn } from "@/lib/api/entityJoin";

export interface ColumnDetailPanelProps {
  column: ColumnTypeInfo | null;
  tables: TableInfo[];
  referenceTableColumns: Record<string, ReferenceTableColumn[]>;
  secondLevelMenus: SecondLevelMenu[];
  numberingRules: any[];
  onColumnChange: (field: keyof ColumnTypeInfo, value: unknown) => void;
  onClose: () => void;
  onLoadReferenceColumns?: (tableName: string) => void;
  /** 코드 카테고리 옵션 (value, label) */
  codeCategoryOptions?: Array<{ value: string; label: string }>;
  /** 참조 테이블 옵션 (value, label) */
  referenceTableOptions?: Array<{ value: string; label: string }>;
}

export function ColumnDetailPanel({
  column,
  tables,
  referenceTableColumns,
  numberingRules,
  onColumnChange,
  onClose,
  onLoadReferenceColumns,
  codeCategoryOptions = [],
  referenceTableOptions = [],
}: ColumnDetailPanelProps) {
  const [advancedOpen, setAdvancedOpen] = React.useState(false);
  const [entityTableOpen, setEntityTableOpen] = React.useState(false);
  const [entityColumnOpen, setEntityColumnOpen] = React.useState(false);

  const typeConf = column ? INPUT_TYPE_COLORS[column.inputType || "text"] : null;
  const refColumns = column?.referenceTable
    ? referenceTableColumns[column.referenceTable] ?? []
    : [];

  React.useEffect(() => {
    if (column?.referenceTable && column.referenceTable !== "none") {
      onLoadReferenceColumns?.(column.referenceTable);
    }
  }, [column?.referenceTable, onLoadReferenceColumns]);

  const advancedCount = useMemo(() => {
    if (!column) return 0;
    let n = 0;
    if (column.defaultValue != null && column.defaultValue !== "") n++;
    if (column.maxLength != null && column.maxLength > 0) n++;
    return n;
  }, [column]);

  if (!column) return null;

  const refTableOpts = useMemo(() => {
    const hasKorean = (s: string) => /[가-힣]/.test(s);
    const raw = referenceTableOptions.length
      ? [...referenceTableOptions]
      : [
          { value: "none", label: "없음" },
          ...tables.map((t) => ({
            value: t.tableName,
            label:
              t.displayName && t.displayName !== t.tableName
                ? `${t.displayName} (${t.tableName})`
                : t.tableName,
          })),
        ];

    const noneOpt = raw.find((o) => o.value === "none");
    const rest = raw.filter((o) => o.value !== "none");

    rest.sort((a, b) => {
      const aK = hasKorean(a.label);
      const bK = hasKorean(b.label);
      if (aK && !bK) return -1;
      if (!aK && bK) return 1;
      return a.label.localeCompare(b.label, "ko");
    });

    return noneOpt ? [noneOpt, ...rest] : rest;
  }, [referenceTableOptions, tables]);

  return (
    <div className="flex h-full w-full flex-col border-l bg-card">
      {/* 헤더 */}
      <div className="flex flex-shrink-0 items-center justify-between border-b px-4 py-3">
        <div className="flex min-w-0 items-center gap-2">
          {typeConf && (
            <span className={cn("rounded px-2 py-0.5 text-xs", typeConf.bgColor, typeConf.color)}>
              {typeConf.label}
            </span>
          )}
          <span className="truncate text-sm font-medium">
            {column.displayName && column.displayName !== column.columnName
              ? `${column.displayName} (${column.columnName})`
              : column.columnName}
          </span>
        </div>
        <Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={onClose} aria-label="닫기">
          <X className="h-4 w-4" />
        </Button>
      </div>

      <div className="flex-1 space-y-4 overflow-y-auto p-4">
        {/* [섹션 1] 데이터 타입 선택 */}
        <section className="space-y-2">
          <div>
            <p className="text-sm font-semibold">이 필드는 어떤 유형인가요?</p>
            <p className="text-xs text-muted-foreground">유형에 따라 입력 방식이 바뀌어요</p>
          </div>
          <div className="grid grid-cols-3 gap-1.5">
            {Object.entries(INPUT_TYPE_COLORS).map(([type, conf]) => {
              const isSelected = (column.inputType || "text") === type;
              return (
                <button
                  key={type}
                  type="button"
                  onClick={() => onColumnChange("inputType", type)}
                  className={cn(
                    "flex flex-col items-center gap-1 rounded-lg border px-1.5 py-2.5 text-center transition-all",
                    isSelected
                      ? "border-primary bg-primary/5 ring-1 ring-primary/30"
                      : "border-border hover:border-primary/30 hover:bg-accent/50",
                  )}
                >
                  <span className={cn(
                    "text-base font-bold leading-none",
                    isSelected ? "text-primary" : conf.color,
                  )}>
                    {conf.iconChar}
                  </span>
                  <span className={cn(
                    "text-[16px] font-semibold leading-tight",
                    isSelected ? "text-primary" : "text-foreground",
                  )}>
                    {conf.label}
                  </span>
                  <span className="text-[12px] leading-tight text-muted-foreground">
                    {conf.desc}
                  </span>
                </button>
              );
            })}
          </div>
        </section>

        {/* [섹션 2] 타입별 상세 설정 */}
        {column.inputType === "entity" && (
          <section className="space-y-3">
            <div className="flex items-center gap-2">
              <Settings2 className="h-4 w-4 text-muted-foreground" />
              <Label className="text-sm font-medium">엔티티 참조</Label>
            </div>

            {/* 참조 테이블 */}
            <div className="space-y-1">
              <Label className="text-[11px] font-medium text-muted-foreground">참조 테이블</Label>
              <Popover open={entityTableOpen} onOpenChange={setEntityTableOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    className="h-9 w-full justify-between text-xs"
                  >
                    {column.referenceTable && column.referenceTable !== "none"
                      ? refTableOpts.find((o) => o.value === column.referenceTable)?.label ?? column.referenceTable
                      : "테이블 선택..."}
                    <ChevronsUpDown className="ml-2 h-3 w-3 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[280px] p-0" align="start">
                  <Command>
                    <CommandInput placeholder="테이블 검색..." className="h-8 text-xs" />
                    <CommandList className="max-h-[200px]">
                      <CommandEmpty className="py-2 text-center text-xs">테이블을 찾을 수 없습니다.</CommandEmpty>
                      <CommandGroup>
                        {refTableOpts.map((opt) => {
                          const hasKorean = opt.value !== "none" && opt.label !== opt.value && !opt.label.startsWith(opt.value);
                          return (
                            <CommandItem
                              key={opt.value}
                              value={`${opt.label} ${opt.value}`}
                              onSelect={() => {
                                onColumnChange("referenceTable", opt.value === "none" ? undefined : opt.value);
                                if (opt.value !== "none") onLoadReferenceColumns?.(opt.value);
                                setEntityTableOpen(false);
                              }}
                              className="text-xs"
                            >
                              <Check
                                className={cn("mr-2 h-3 w-3", column.referenceTable === opt.value ? "opacity-100" : "opacity-0")}
                              />
                              {hasKorean ? (
                                <div className="flex flex-col">
                                  <span className="font-medium">{opt.label.replace(` (${opt.value})`, "")}</span>
                                  <span className="text-[10px] text-muted-foreground">{opt.value}</span>
                                </div>
                              ) : (
                                opt.label
                              )}
                            </CommandItem>
                          );
                        })}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </div>

            {/* 조인 컬럼 */}
            {column.referenceTable && column.referenceTable !== "none" && (
              <div className="space-y-1">
                <Label className="text-[11px] font-medium text-muted-foreground">조인 컬럼(값)</Label>
                <Popover open={entityColumnOpen} onOpenChange={setEntityColumnOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      disabled={refColumns.length === 0}
                      className="h-9 w-full justify-between text-xs"
                    >
                      {column.referenceColumn && column.referenceColumn !== "none"
                        ? (() => {
                            const matched = refColumns.find((c) => c.columnName === column.referenceColumn);
                            return matched?.displayName && matched.displayName !== column.referenceColumn
                              ? `${matched.displayName} (${column.referenceColumn})`
                              : column.referenceColumn;
                          })()
                        : "컬럼 선택..."}
                      <ChevronsUpDown className="ml-2 h-3 w-3 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[280px] p-0" align="start">
                    <Command>
                      <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                      <CommandList className="max-h-[200px]">
                        <CommandEmpty className="py-2 text-center text-xs">컬럼을 찾을 수 없습니다.</CommandEmpty>
                        <CommandGroup>
                          <CommandItem
                            value="none"
                            onSelect={() => {
                              onColumnChange("referenceColumn", undefined);
                              setEntityColumnOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check className={cn("mr-2 h-3 w-3", !column.referenceColumn ? "opacity-100" : "opacity-0")} />
                            선택 안함
                          </CommandItem>
                          {refColumns.map((refCol) => (
                            <CommandItem
                              key={refCol.columnName}
                              value={`${refCol.displayName ?? ""} ${refCol.columnName}`}
                              onSelect={() => {
                                onColumnChange("referenceColumn", refCol.columnName);
                                setEntityColumnOpen(false);
                              }}
                              className="text-xs"
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-3 w-3",
                                  column.referenceColumn === refCol.columnName ? "opacity-100" : "opacity-0",
                                )}
                              />
                              {refCol.displayName && refCol.displayName !== refCol.columnName ? (
                                <div className="flex flex-col">
                                  <span className="font-medium">{refCol.displayName}</span>
                                  <span className="text-[10px] text-muted-foreground">{refCol.columnName}</span>
                                </div>
                              ) : (
                                <span>{refCol.columnName}</span>
                              )}
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </CommandList>
                    </Command>
                  </PopoverContent>
                </Popover>
              </div>
            )}

            {/* 참조 요약 미니맵 */}
            {column.referenceTable && column.referenceTable !== "none" && column.referenceColumn && (
              <div className="flex items-center gap-2 rounded-md bg-violet-50 px-3 py-2">
                <span className="text-[11px] font-semibold text-violet-600">
                  {(() => {
                    const tbl = refTableOpts.find((o) => o.value === column.referenceTable);
                    return tbl?.label ?? column.referenceTable;
                  })()}
                </span>
                <span className="text-muted-foreground text-[10px]">→</span>
                <span className="text-[11px] font-semibold text-violet-600">
                  {(() => {
                    const col = refColumns.find((c) => c.columnName === column.referenceColumn);
                    return col?.displayName && col.displayName !== column.referenceColumn
                      ? `${col.displayName} (${column.referenceColumn})`
                      : column.referenceColumn;
                  })()}
                </span>
              </div>
            )}
          </section>
        )}

        {column.inputType === "code" && (
          <section className="space-y-2">
            <div className="flex items-center gap-2">
              <Settings2 className="h-4 w-4 text-muted-foreground" />
              <Label className="text-sm font-medium">코드 설정</Label>
            </div>
            <div className="space-y-2">
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">공통코드 카테고리</Label>
                <Select
                  value={column.codeCategory ?? "none"}
                  onValueChange={(v) => onColumnChange("codeCategory", v === "none" ? undefined : v)}
                >
                  <SelectTrigger className="h-9 text-xs">
                    <SelectValue placeholder="코드 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {[{ value: "none", label: "선택 안함" }, ...codeCategoryOptions].map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              {column.codeCategory && column.codeCategory !== "none" && (
                <div className="space-y-1.5">
                  <Label className="text-xs text-muted-foreground">계층 역할</Label>
                  <Select
                    value={column.hierarchyRole ?? "none"}
                    onValueChange={(v) =>
                      onColumnChange("hierarchyRole", v === "none" ? undefined : (v as "large" | "medium" | "small"))
                    }
                  >
                    <SelectTrigger className="h-9 text-xs">
                      <SelectValue placeholder="일반" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">일반</SelectItem>
                      <SelectItem value="large">대분류</SelectItem>
                      <SelectItem value="medium">중분류</SelectItem>
                      <SelectItem value="small">소분류</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>
          </section>
        )}

        {column.inputType === "category" && (
          <section className="space-y-2">
            <div className="flex items-center gap-2">
              <Settings2 className="h-4 w-4 text-muted-foreground" />
              <Label className="text-sm font-medium">카테고리 참조</Label>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">참조 (테이블.컬럼)</Label>
              <Input
                value={column.categoryRef ?? ""}
                onChange={(e) => onColumnChange("categoryRef", e.target.value || null)}
                placeholder="테이블명.컬럼명"
                className="h-9 text-xs"
              />
            </div>
          </section>
        )}

        {column.inputType === "numbering" && (
          <section className="space-y-2">
            <div className="flex items-center gap-2">
              <Settings2 className="h-4 w-4 text-muted-foreground" />
              <Label className="text-sm font-medium">채번 규칙</Label>
            </div>
            <p className="rounded-md border border-border bg-muted/50 px-3 py-2 text-xs text-muted-foreground">
              채번 규칙은 옵션설정 &gt; 채번설정에서 관리합니다.
              타입을 저장하면 자동으로 채번 목록에 표시됩니다.
            </p>
          </section>
        )}

        {/* [섹션 3] 표시 이름 */}
        <section className="space-y-2">
          <div className="flex items-center gap-2">
            <Tag className="h-4 w-4 text-muted-foreground" />
            <Label className="text-sm font-medium">표시 이름</Label>
          </div>
          <Input
            value={column.displayName ?? ""}
            onChange={(e) => onColumnChange("displayName", e.target.value)}
            placeholder={column.columnName}
            className="h-9 text-sm"
          />
        </section>

        {/* [섹션 4] 표시 옵션 */}
        <section className="space-y-2">
          <div className="flex items-center gap-2">
            <ToggleLeft className="h-4 w-4 text-muted-foreground" />
            <Label className="text-sm font-medium">표시 옵션</Label>
          </div>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium">필수 입력</p>
                <p className="text-xs text-muted-foreground">비워두면 저장할 수 없어요.</p>
              </div>
              <Switch
                checked={column.isNullable === "NO"}
                onCheckedChange={(checked) => onColumnChange("isNullable", checked ? "NO" : "YES")}
                aria-label="필수 입력"
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium">읽기 전용</p>
                <p className="text-xs text-muted-foreground">편집할 수 없어요.</p>
              </div>
              <Switch
                checked={false}
                onCheckedChange={() => {}}
                disabled
                aria-label="읽기 전용 (향후 확장)"
              />
            </div>
          </div>
        </section>

        {/* [섹션 5] 고급 설정 */}
        <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
          <CollapsibleTrigger asChild>
            <button
              type="button"
              className="flex w-full items-center justify-between py-1 text-left"
              aria-expanded={advancedOpen}
            >
              <div className="flex items-center gap-2">
                {advancedOpen ? (
                  <ChevronDown className="h-4 w-4 text-muted-foreground" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-muted-foreground" />
                )}
                <span className="text-sm font-medium">고급 설정</span>
                {advancedCount > 0 && (
                  <Badge variant="secondary" className="text-xs">
                    {advancedCount}개 설정됨
                  </Badge>
                )}
              </div>
            </button>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <div className="space-y-3 pt-2">
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">기본값</Label>
                <Input
                  value={column.defaultValue ?? ""}
                  onChange={(e) => onColumnChange("defaultValue", e.target.value)}
                  placeholder="기본값"
                  className="h-9 text-xs"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">최대 길이</Label>
                <Input
                  type="number"
                  value={column.maxLength ?? ""}
                  onChange={(e) => {
                    const v = e.target.value;
                    onColumnChange("maxLength", v === "" ? undefined : Number(v));
                  }}
                  placeholder="숫자"
                  className="h-9 text-xs"
                />
              </div>
            </div>
          </CollapsibleContent>
        </Collapsible>
      </div>
    </div>
  );
}
