"use client";

/**
 * V2SplitLine 설정 패널
 * 토스식 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 } from "lucide-react";
import { cn } from "@/lib/utils";

const WIDTH_CARDS = [
  { value: 2, label: "얇게" },
  { value: 4, label: "보통" },
  { value: 6, label: "두껍게" },
  { value: 8, label: "넓게" },
] as const;

const COLOR_CARDS = [
  { value: "#e2e8f0", label: "기본", description: "연한 회색" },
  { value: "#94a3b8", label: "진하게", description: "중간 회색" },
  { value: "#3b82f6", label: "강조", description: "파란색" },
] as const;

interface V2SplitLineConfigPanelProps {
  config: Record<string, any>;
  onConfigChange: (config: Record<string, any>) => void;
}

export const V2SplitLineConfigPanel: React.FC<V2SplitLineConfigPanelProps> = ({
  config,
  onConfigChange,
}) => {
  const [advancedOpen, setAdvancedOpen] = useState(false);
  const currentConfig = config || {};

  const updateConfig = (field: string, value: any) => {
    const newConfig = { ...currentConfig, [field]: value };
    onConfigChange(newConfig);

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

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 드래그 리사이즈 ─── */}
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium">드래그 리사이즈</p>
          <p className="text-[11px] text-muted-foreground">
            런타임에서 드래그로 좌우 영역을 조절할 수 있어요
          </p>
        </div>
        <Switch
          checked={currentConfig.resizable ?? true}
          onCheckedChange={(checked) => updateConfig("resizable", checked)}
        />
      </div>

      {/* ─── 2단계: 분할선 두께 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">분할선 두께</p>
        <div className="grid grid-cols-4 gap-2">
          {WIDTH_CARDS.map((card) => {
            const isSelected = (currentConfig.lineWidth || 4) === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("lineWidth", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-2 text-center transition-all min-h-[52px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <div
                  className="mb-1.5 h-6 rounded-sm"
                  style={{
                    width: `${card.value}px`,
                    backgroundColor: currentConfig.lineColor || "#e2e8f0",
                    border: "1px solid rgba(0,0,0,0.1)",
                  }}
                />
                <span className="text-[10px] font-medium">{card.label}</span>
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-muted-foreground">
          현재: {currentConfig.lineWidth || 4}px
        </p>
      </div>

      {/* ─── 3단계: 분할선 색상 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">분할선 색상</p>
        <div className="grid grid-cols-3 gap-2">
          {COLOR_CARDS.map((card) => {
            const isSelected =
              (currentConfig.lineColor || "#e2e8f0") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("lineColor", card.value)}
                className={cn(
                  "flex flex-col items-center rounded-md border p-2 text-center transition-all",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <div
                  className="mb-1 h-3 w-3 rounded-full"
                  style={{ backgroundColor: card.value }}
                />
                <span className="text-xs font-medium">{card.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 고급 설정: 커스텀 색상 입력 ─── */}
      <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">
              <span className="text-xs text-muted-foreground">직접 입력</span>
              <div className="flex items-center gap-1.5">
                <input
                  type="color"
                  value={currentConfig.lineColor || "#e2e8f0"}
                  onChange={(e) => updateConfig("lineColor", e.target.value)}
                  className="h-7 w-7 cursor-pointer rounded border"
                />
                <Input
                  value={currentConfig.lineColor || "#e2e8f0"}
                  onChange={(e) => updateConfig("lineColor", e.target.value)}
                  placeholder="#e2e8f0"
                  className="h-7 w-[100px] text-xs"
                />
              </div>
            </div>

            {/* 커스텀 두께 입력 */}
            <div className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">두께 직접 입력 (px)</span>
              <Input
                type="number"
                value={currentConfig.lineWidth || 4}
                onChange={(e) =>
                  updateConfig("lineWidth", parseInt(e.target.value) || 4)
                }
                className="h-7 w-[80px] text-xs"
                min={1}
                max={12}
              />
            </div>
          </div>
        </CollapsibleContent>
      </Collapsible>

      <p className="text-[10px] text-muted-foreground">
        캔버스에서 스플릿선의 X 위치가 초기 분할 지점이 돼요. 런타임에서
        드래그하면 좌우 컴포넌트가 함께 이동해요.
      </p>
    </div>
  );
};

V2SplitLineConfigPanel.displayName = "V2SplitLineConfigPanel";

export default V2SplitLineConfigPanel;
