"use client";

import React from "react";
import { Plus, Trash2, GripVertical } 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 { ProcessWorkStandardConfig, WorkPhaseDefinition, DetailTypeDefinition } from "./types";
import { defaultConfig } from "./config";

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

export function ProcessWorkStandardConfigPanel({
  config: configProp,
  onChange,
}: ConfigPanelProps) {
  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-5 p-4">
      <h3 className="text-sm font-semibold">공정 작업기준 설정</h3>

      {/* 데이터 소스 설정 */}
      <section className="space-y-3">
        <p className="text-xs font-medium text-muted-foreground">데이터 소스 설정</p>

        <div>
          <Label className="text-xs">품목 테이블</Label>
          <Input
            value={config.dataSource.itemTable}
            onChange={(e) => updateDataSource("itemTable", e.target.value)}
            className="mt-1 h-8 text-xs"
          />
        </div>
        <div className="grid grid-cols-2 gap-2">
          <div>
            <Label className="text-xs">품목명 컬럼</Label>
            <Input
              value={config.dataSource.itemNameColumn}
              onChange={(e) => updateDataSource("itemNameColumn", e.target.value)}
              className="mt-1 h-8 text-xs"
            />
          </div>
          <div>
            <Label className="text-xs">품목코드 컬럼</Label>
            <Input
              value={config.dataSource.itemCodeColumn}
              onChange={(e) => updateDataSource("itemCodeColumn", e.target.value)}
              className="mt-1 h-8 text-xs"
            />
          </div>
        </div>

        <div>
          <Label className="text-xs">라우팅 버전 테이블</Label>
          <Input
            value={config.dataSource.routingVersionTable}
            onChange={(e) => updateDataSource("routingVersionTable", e.target.value)}
            className="mt-1 h-8 text-xs"
          />
        </div>
        <div>
          <Label className="text-xs">품목 연결 FK 컬럼</Label>
          <Input
            value={config.dataSource.routingFkColumn}
            onChange={(e) => updateDataSource("routingFkColumn", e.target.value)}
            className="mt-1 h-8 text-xs"
          />
        </div>

        <div>
          <Label className="text-xs">공정 마스터 테이블</Label>
          <Input
            value={config.dataSource.processTable}
            onChange={(e) => updateDataSource("processTable", e.target.value)}
            className="mt-1 h-8 text-xs"
          />
        </div>
        <div className="grid grid-cols-2 gap-2">
          <div>
            <Label className="text-xs">공정명 컬럼</Label>
            <Input
              value={config.dataSource.processNameColumn}
              onChange={(e) => updateDataSource("processNameColumn", e.target.value)}
              className="mt-1 h-8 text-xs"
            />
          </div>
          <div>
            <Label className="text-xs">공정코드 컬럼</Label>
            <Input
              value={config.dataSource.processCodeColumn}
              onChange={(e) => updateDataSource("processCodeColumn", e.target.value)}
              className="mt-1 h-8 text-xs"
            />
          </div>
        </div>
      </section>

      {/* 작업 단계 설정 */}
      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-xs font-medium text-muted-foreground">작업 단계 설정</p>
          <Button variant="outline" size="sm" className="h-6 gap-1 text-[10px]" onClick={addPhase}>
            <Plus className="h-3 w-3" />
            단계 추가
          </Button>
        </div>

        <div className="space-y-1.5">
          {config.phases.map((phase, idx) => (
            <div
              key={idx}
              className="flex items-center gap-1.5 rounded border bg-muted/30 p-1.5"
            >
              <GripVertical className="h-3.5 w-3.5 shrink-0 text-muted-foreground/50" />
              <Input
                value={phase.key}
                onChange={(e) => updatePhase(idx, "key", e.target.value)}
                className="h-7 w-20 text-[10px]"
                placeholder="키"
              />
              <Input
                value={phase.label}
                onChange={(e) => updatePhase(idx, "label", e.target.value)}
                className="h-7 flex-1 text-[10px]"
                placeholder="표시명"
              />
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 shrink-0 text-destructive hover:text-destructive"
                onClick={() => removePhase(idx)}
                disabled={config.phases.length <= 1}
              >
                <Trash2 className="h-3 w-3" />
              </Button>
            </div>
          ))}
        </div>
      </section>

      {/* 상세 유형 옵션 */}
      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-xs font-medium text-muted-foreground">상세 유형 옵션</p>
          <Button
            variant="outline"
            size="sm"
            className="h-6 gap-1 text-[10px]"
            onClick={addDetailType}
          >
            <Plus className="h-3 w-3" />
            유형 추가
          </Button>
        </div>

        <div className="space-y-1.5">
          {config.detailTypes.map((dt, idx) => (
            <div key={idx} className="flex items-center gap-1.5 rounded border bg-muted/30 p-1.5">
              <Input
                value={dt.value}
                onChange={(e) => updateDetailType(idx, "value", e.target.value)}
                className="h-7 w-24 text-[10px]"
                placeholder="값"
              />
              <Input
                value={dt.label}
                onChange={(e) => updateDetailType(idx, "label", e.target.value)}
                className="h-7 flex-1 text-[10px]"
                placeholder="표시명"
              />
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 shrink-0 text-destructive hover:text-destructive"
                onClick={() => removeDetailType(idx)}
                disabled={config.detailTypes.length <= 1}
              >
                <Trash2 className="h-3 w-3" />
              </Button>
            </div>
          ))}
        </div>
      </section>

      {/* UI 설정 */}
      <section className="space-y-3">
        <p className="text-xs font-medium text-muted-foreground">UI 설정</p>

        <div>
          <Label className="text-xs">좌우 분할 비율 (%)</Label>
          <Input
            type="number"
            value={config.splitRatio || 30}
            onChange={(e) => update({ splitRatio: Number(e.target.value) })}
            min={15}
            max={50}
            className="mt-1 h-8 w-20 text-xs"
          />
        </div>

        <div>
          <Label className="text-xs">좌측 패널 제목</Label>
          <Input
            value={config.leftPanelTitle || ""}
            onChange={(e) => update({ leftPanelTitle: e.target.value })}
            className="mt-1 h-8 text-xs"
          />
        </div>

        <div className="flex items-center gap-2">
          <Switch
            checked={config.readonly || false}
            onCheckedChange={(v) => update({ readonly: v })}
          />
          <Label className="text-xs">읽기 전용 모드</Label>
        </div>
      </section>
    </div>
  );
}
