"use client";

/**
 * V2NumberingRule 설정 패널
 * 토스식 단계별 UX: 최대 규칙 수(카드선택) -> 카드 레이아웃(카드선택) -> 표시/동작(Switch) -> 고급(접힘)
 */

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Settings, ChevronDown, LayoutList, LayoutGrid } from "lucide-react";
import { cn } from "@/lib/utils";
import { NumberingRuleComponentConfig } from "@/lib/registry/components/v2-numbering-rule/types";

const MAX_RULES_CARDS = [
  { value: 3, label: "3개", desc: "간단한 코드" },
  { value: 6, label: "6개", desc: "기본 (권장)" },
  { value: 8, label: "8개", desc: "복잡한 코드" },
  { value: 10, label: "10개", desc: "최대" },
] as const;

const LAYOUT_CARDS = [
  { value: "vertical", label: "세로", desc: "위에서 아래로", icon: LayoutList },
  { value: "horizontal", label: "가로", desc: "왼쪽에서 오른쪽으로", icon: LayoutGrid },
] as const;

interface V2NumberingRuleConfigPanelProps {
  config: NumberingRuleComponentConfig;
  onChange: (config: NumberingRuleComponentConfig) => void;
}

export const V2NumberingRuleConfigPanel: React.FC<V2NumberingRuleConfigPanelProps> = ({
  config,
  onChange,
}) => {
  const [advancedOpen, setAdvancedOpen] = useState(false);

  const updateConfig = (field: keyof NumberingRuleComponentConfig, value: any) => {
    const newConfig = { ...config, [field]: value };
    onChange(newConfig);

    if (typeof window !== "undefined") {
      window.dispatchEvent(
        new CustomEvent("componentConfigChanged", {
          detail: { config: newConfig },
        })
      );
    }
  };

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 최대 규칙 수 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">최대 파트 수</p>
        <div className="grid grid-cols-4 gap-2">
          {MAX_RULES_CARDS.map((card) => {
            const isSelected = (config.maxRules || 6) === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("maxRules", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-2.5 text-center transition-all min-h-[60px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <span className="text-xs font-medium">{card.label}</span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  {card.desc}
                </span>
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-muted-foreground">
          하나의 채번 규칙에 추가할 수 있는 최대 파트 개수에요
        </p>
      </div>

      {/* ─── 2단계: 카드 레이아웃 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">파트 배치 방향</p>
        <div className="grid grid-cols-2 gap-2">
          {LAYOUT_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = (config.cardLayout || "vertical") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("cardLayout", card.value)}
                className={cn(
                  "flex items-center gap-2 rounded-lg border p-3 text-left transition-all",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <Icon className="h-5 w-5 shrink-0 text-muted-foreground" />
                <div>
                  <span className="text-xs font-medium block">{card.label}</span>
                  <span className="text-[10px] text-muted-foreground block">
                    {card.desc}
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 3단계: 표시 설정 (Switch) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">표시 설정</p>
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">미리보기 표시</p>
              <p className="text-[11px] text-muted-foreground">
                코드 미리보기를 항상 보여줘요
              </p>
            </div>
            <Switch
              checked={config.showPreview !== false}
              onCheckedChange={(checked) => updateConfig("showPreview", checked)}
            />
          </div>
          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">규칙 목록 표시</p>
              <p className="text-[11px] text-muted-foreground">
                저장된 규칙 목록을 보여줘요
              </p>
            </div>
            <Switch
              checked={config.showRuleList !== false}
              onCheckedChange={(checked) => updateConfig("showRuleList", checked)}
            />
          </div>
          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">파트 순서 변경</p>
              <p className="text-[11px] text-muted-foreground">
                파트 드래그로 순서를 바꿀 수 있어요
              </p>
            </div>
            <Switch
              checked={config.enableReorder !== false}
              onCheckedChange={(checked) => updateConfig("enableReorder", checked)}
            />
          </div>
        </div>
      </div>

      {/* ─── 4단계: 고급 설정 (기본 접혀있음) ─── */}
      <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-4 space-y-3">
            <div className="flex items-center justify-between py-1">
              <div>
                <p className="text-sm">읽기 전용</p>
                <p className="text-[11px] text-muted-foreground">
                  편집 기능을 비활성화해요
                </p>
              </div>
              <Switch
                checked={config.readonly || false}
                onCheckedChange={(checked) => updateConfig("readonly", checked)}
              />
            </div>
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2NumberingRuleConfigPanel.displayName = "V2NumberingRuleConfigPanel";

export default V2NumberingRuleConfigPanel;
