"use client";

/**
 * V2 공정 작업기준 설정 패널
 * Progressive Disclosure: 작업 단계 -> 상세 유형 -> 고급 설정(접힘)
 */

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Badge } from "@/components/ui/badge";
import { Settings, ChevronDown, ChevronRight, Plus, Trash2, Database, Layers, List } from "lucide-react";
import { cn } from "@/lib/utils";
import type {
  ProcessWorkStandardConfig,
  WorkPhaseDefinition,
  DetailTypeDefinition,
} from "@/lib/registry/components/v2-process-work-standard/types";
import { defaultConfig } from "@/lib/registry/components/v2-process-work-standard/config";

interface V2ProcessWorkStandardConfigPanelProps {
  config: Partial<ProcessWorkStandardConfig>;
  onChange: (config: Partial<ProcessWorkStandardConfig>) => void;
}

export const V2ProcessWorkStandardConfigPanel: React.FC<V2ProcessWorkStandardConfigPanelProps> = ({
  config: configProp,
  onChange,
}) => {
  const [phasesOpen, setPhasesOpen] = useState(false);
  const [detailTypesOpen, setDetailTypesOpen] = useState(false);
  const [advancedOpen, setAdvancedOpen] = useState(false);
  const [dataSourceOpen, setDataSourceOpen] = useState(false);

  const config: ProcessWorkStandardConfig = {
    ...defaultConfig,
    ...configProp,
    dataSource: { ...defaultConfig.dataSource, ...configProp?.dataSource },
    phases: configProp?.phases?.length ? configProp.phases : defaultConfig.phases,
    detailTypes: configProp?.detailTypes?.length ? configProp.detailTypes : defaultConfig.detailTypes,
  };

  const update = (partial: Partial<ProcessWorkStandardConfig>) => {
    onChange({ ...configProp, ...partial });
  };

  const updateDataSource = (field: string, value: string) => {
    update({ dataSource: { ...config.dataSource, [field]: value } });
  };

  // ─── 작업 단계 관리 ───
  const addPhase = () => {
    const nextOrder = config.phases.length + 1;
    update({
      phases: [
        ...config.phases,
        { key: `PHASE_${nextOrder}`, label: `단계 ${nextOrder}`, sortOrder: nextOrder },
      ],
    });
  };

  const removePhase = (idx: number) => {
    update({ phases: config.phases.filter((_, i) => i !== idx) });
  };

  const updatePhase = (idx: number, field: keyof WorkPhaseDefinition, value: string | number) => {
    const next = [...config.phases];
    next[idx] = { ...next[idx], [field]: value };
    update({ phases: next });
  };

  // ─── 상세 유형 관리 ───
  const addDetailType = () => {
    update({
      detailTypes: [
        ...config.detailTypes,
        { value: `TYPE_${config.detailTypes.length + 1}`, label: "신규 유형" },
      ],
    });
  };

  const removeDetailType = (idx: number) => {
    update({ detailTypes: config.detailTypes.filter((_, i) => i !== idx) });
  };

  const updateDetailType = (idx: number, field: keyof DetailTypeDefinition, value: string) => {
    const next = [...config.detailTypes];
    next[idx] = { ...next[idx], [field]: value };
    update({ detailTypes: next });
  };

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 작업 단계 설정 (Collapsible + 접이식 카드) ─── */}
      <Collapsible open={phasesOpen} onOpenChange={setPhasesOpen}>
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex w-full items-center justify-between rounded-lg border bg-muted/30 px-4 py-2.5 text-left transition-colors hover:bg-muted/50"
          >
            <div className="flex items-center gap-2">
              <Layers className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">작업 단계</span>
              <Badge variant="secondary" className="text-[10px] h-5">
                {config.phases.length}개
              </Badge>
            </div>
            <ChevronDown
              className={cn(
                "h-4 w-4 text-muted-foreground transition-transform duration-200",
                phasesOpen && "rotate-180",
              )}
            />
          </button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="rounded-b-lg border border-t-0 p-3 space-y-1.5">
            <p className="text-[10px] text-muted-foreground mb-1">공정별 작업 단계(Phase)를 정의</p>
            <div className="space-y-1">
              {config.phases.map((phase, idx) => (
                <Collapsible key={idx}>
                  <div className="rounded-md border">
                    <CollapsibleTrigger asChild>
                      <button
                        type="button"
                        className="flex w-full items-center gap-1.5 px-2.5 py-1.5 text-left hover:bg-muted/30 transition-colors"
                      >
                        <ChevronRight className="h-3 w-3 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90 shrink-0" />
                        <span className="text-[10px] text-muted-foreground font-medium shrink-0">#{idx + 1}</span>
                        <span className="text-xs font-medium truncate flex-1 min-w-0">{phase.label}</span>
                        <Badge variant="outline" className="text-[9px] h-4 shrink-0">{phase.key}</Badge>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={(e) => { e.stopPropagation(); removePhase(idx); }}
                          className="h-5 w-5 p-0 text-muted-foreground hover:text-destructive shrink-0"
                          disabled={config.phases.length <= 1}
                        >
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </button>
                    </CollapsibleTrigger>
                    <CollapsibleContent>
                      <div className="grid grid-cols-3 gap-1.5 border-t px-2.5 py-2">
                        <div className="space-y-0.5">
                          <span className="text-[10px] text-muted-foreground">키</span>
                          <Input
                            value={phase.key}
                            onChange={(e) => updatePhase(idx, "key", e.target.value)}
                            className="h-7 text-xs"
                            placeholder="키"
                          />
                        </div>
                        <div className="space-y-0.5">
                          <span className="text-[10px] text-muted-foreground">표시명</span>
                          <Input
                            value={phase.label}
                            onChange={(e) => updatePhase(idx, "label", e.target.value)}
                            className="h-7 text-xs"
                            placeholder="표시명"
                          />
                        </div>
                        <div className="space-y-0.5">
                          <span className="text-[10px] text-muted-foreground">순서</span>
                          <Input
                            type="number"
                            min={1}
                            value={phase.sortOrder}
                            onChange={(e) => updatePhase(idx, "sortOrder", parseInt(e.target.value) || 1)}
                            className="h-7 text-xs text-center"
                            placeholder="1"
                          />
                        </div>
                      </div>
                    </CollapsibleContent>
                  </div>
                </Collapsible>
              ))}
            </div>
            <Button
              variant="outline"
              size="sm"
              className="h-7 w-full gap-1 text-xs border-dashed"
              onClick={addPhase}
            >
              <Plus className="h-3 w-3" />
              단계 추가
            </Button>
          </div>
        </CollapsibleContent>
      </Collapsible>

      {/* ─── 2단계: 상세 유형 옵션 (Collapsible + 접이식 카드) ─── */}
      <Collapsible open={detailTypesOpen} onOpenChange={setDetailTypesOpen}>
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex w-full items-center justify-between rounded-lg border bg-muted/30 px-4 py-2.5 text-left transition-colors hover:bg-muted/50"
          >
            <div className="flex items-center gap-2">
              <List className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">상세 유형</span>
              <Badge variant="secondary" className="text-[10px] h-5">
                {config.detailTypes.length}개
              </Badge>
            </div>
            <ChevronDown
              className={cn(
                "h-4 w-4 text-muted-foreground transition-transform duration-200",
                detailTypesOpen && "rotate-180",
              )}
            />
          </button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="rounded-b-lg border border-t-0 p-3 space-y-1.5">
            <p className="text-[10px] text-muted-foreground mb-1">작업 항목의 상세 유형 드롭다운 옵션</p>
            <div className="space-y-1">
              {config.detailTypes.map((dt, idx) => (
                <Collapsible key={idx}>
                  <div className="rounded-md border">
                    <CollapsibleTrigger asChild>
                      <button
                        type="button"
                        className="flex w-full items-center gap-1.5 px-2.5 py-1.5 text-left hover:bg-muted/30 transition-colors"
                      >
                        <ChevronRight className="h-3 w-3 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90 shrink-0" />
                        <span className="text-[10px] text-muted-foreground font-medium shrink-0">#{idx + 1}</span>
                        <span className="text-xs font-medium truncate flex-1 min-w-0">{dt.label}</span>
                        <Badge variant="outline" className="text-[9px] h-4 shrink-0">{dt.value}</Badge>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={(e) => { e.stopPropagation(); removeDetailType(idx); }}
                          className="h-5 w-5 p-0 text-muted-foreground hover:text-destructive shrink-0"
                          disabled={config.detailTypes.length <= 1}
                        >
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </button>
                    </CollapsibleTrigger>
                    <CollapsibleContent>
                      <div className="grid grid-cols-2 gap-1.5 border-t px-2.5 py-2">
                        <div className="space-y-0.5">
                          <span className="text-[10px] text-muted-foreground">값</span>
                          <Input
                            value={dt.value}
                            onChange={(e) => updateDetailType(idx, "value", e.target.value)}
                            className="h-7 text-xs"
                            placeholder="값"
                          />
                        </div>
                        <div className="space-y-0.5">
                          <span className="text-[10px] text-muted-foreground">표시명</span>
                          <Input
                            value={dt.label}
                            onChange={(e) => updateDetailType(idx, "label", e.target.value)}
                            className="h-7 text-xs"
                            placeholder="표시명"
                          />
                        </div>
                      </div>
                    </CollapsibleContent>
                  </div>
                </Collapsible>
              ))}
            </div>
            <Button
              variant="outline"
              size="sm"
              className="h-7 w-full gap-1 text-xs border-dashed"
              onClick={addDetailType}
            >
              <Plus className="h-3 w-3" />
              유형 추가
            </Button>
          </div>
        </CollapsibleContent>
      </Collapsible>

      {/* ─── 3단계: 고급 설정 (데이터 소스 + 레이아웃 통합) ─── */}
      <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex w-full items-center justify-between rounded-lg border bg-muted/30 px-4 py-2.5 text-left transition-colors hover:bg-muted/50"
          >
            <div className="flex items-center gap-2">
              <Settings className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">고급 설정</span>
            </div>
            <ChevronDown
              className={cn(
                "h-4 w-4 text-muted-foreground transition-transform duration-200",
                advancedOpen && "rotate-180",
              )}
            />
          </button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="rounded-b-lg border border-t-0 p-3 space-y-3">

            {/* 레이아웃 기본 설정 */}
            <div className="space-y-2">
              <div className="flex items-center justify-between py-1">
                <div>
                  <span className="text-xs text-muted-foreground">좌측 패널 비율 (%)</span>
                  <p className="text-[10px] text-muted-foreground mt-0.5">품목/공정 선택 패널의 너비</p>
                </div>
                <Input
                  type="number"
                  min={15}
                  max={50}
                  value={config.splitRatio || 30}
                  onChange={(e) => update({ splitRatio: parseInt(e.target.value) || 30 })}
                  className="h-7 w-[80px] text-xs"
                />
              </div>
              <div className="flex items-center justify-between py-1">
                <span className="text-xs text-muted-foreground">좌측 패널 제목</span>
                <Input
                  value={config.leftPanelTitle || ""}
                  onChange={(e) => update({ leftPanelTitle: e.target.value })}
                  placeholder="품목 및 공정 선택"
                  className="h-7 w-[140px] text-xs"
                />
              </div>
              <div className="flex items-center justify-between py-1">
                <div>
                  <p className="text-xs">읽기 전용</p>
                  <p className="text-[10px] text-muted-foreground">수정/삭제 버튼을 숨겨요</p>
                </div>
                <Switch
                  checked={config.readonly || false}
                  onCheckedChange={(checked) => update({ readonly: checked })}
                />
              </div>
            </div>

            {/* 데이터 소스 (서브 Collapsible) */}
            <Collapsible open={dataSourceOpen} onOpenChange={setDataSourceOpen}>
              <CollapsibleTrigger asChild>
                <button
                  type="button"
                  className="flex w-full items-center justify-between rounded-md border px-3 py-2 transition-colors hover:bg-muted/30"
                >
                  <div className="flex items-center gap-2">
                    <Database className="h-3.5 w-3.5 text-muted-foreground" />
                    <span className="text-xs font-medium">데이터 소스</span>
                    {config.dataSource.itemTable && (
                      <Badge variant="secondary" className="text-[10px] h-5 truncate max-w-[100px]">
                        {config.dataSource.itemTable}
                      </Badge>
                    )}
                  </div>
                  <ChevronDown
                    className={cn(
                      "h-3.5 w-3.5 text-muted-foreground transition-transform",
                      dataSourceOpen && "rotate-180",
                    )}
                  />
                </button>
              </CollapsibleTrigger>
              <CollapsibleContent className="space-y-2 pt-2">
                <div className="space-y-1">
                  <span className="text-[10px] text-muted-foreground">품목 테이블</span>
                  <Input
                    value={config.dataSource.itemTable}
                    onChange={(e) => updateDataSource("itemTable", e.target.value)}
                    className="h-7 w-full text-xs"
                  />
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">품목명 컬럼</span>
                    <Input
                      value={config.dataSource.itemNameColumn}
                      onChange={(e) => updateDataSource("itemNameColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">품목코드 컬럼</span>
                    <Input
                      value={config.dataSource.itemCodeColumn}
                      onChange={(e) => updateDataSource("itemCodeColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                </div>
                <div className="space-y-1 pt-1">
                  <span className="text-[10px] text-muted-foreground">라우팅 버전 테이블</span>
                  <Input
                    value={config.dataSource.routingVersionTable}
                    onChange={(e) => updateDataSource("routingVersionTable", e.target.value)}
                    className="h-7 w-full text-xs"
                  />
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">품목 연결 FK</span>
                    <Input
                      value={config.dataSource.routingFkColumn}
                      onChange={(e) => updateDataSource("routingFkColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">버전명 컬럼</span>
                    <Input
                      value={config.dataSource.routingVersionNameColumn}
                      onChange={(e) => updateDataSource("routingVersionNameColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                </div>
                <div className="space-y-1 pt-1">
                  <span className="text-[10px] text-muted-foreground">라우팅 상세 테이블</span>
                  <Input
                    value={config.dataSource.routingDetailTable}
                    onChange={(e) => updateDataSource("routingDetailTable", e.target.value)}
                    className="h-7 w-full text-xs"
                  />
                </div>
                <div className="space-y-1 pt-1">
                  <span className="text-[10px] text-muted-foreground">공정 마스터 테이블</span>
                  <Input
                    value={config.dataSource.processTable}
                    onChange={(e) => updateDataSource("processTable", e.target.value)}
                    className="h-7 w-full text-xs"
                  />
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">공정명 컬럼</span>
                    <Input
                      value={config.dataSource.processNameColumn}
                      onChange={(e) => updateDataSource("processNameColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[10px] text-muted-foreground">공정코드 컬럼</span>
                    <Input
                      value={config.dataSource.processCodeColumn}
                      onChange={(e) => updateDataSource("processCodeColumn", e.target.value)}
                      className="h-7 text-xs"
                    />
                  </div>
                </div>
              </CollapsibleContent>
            </Collapsible>

          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2ProcessWorkStandardConfigPanel.displayName = "V2ProcessWorkStandardConfigPanel";

export default V2ProcessWorkStandardConfigPanel;
