"use client";

/**
 * V2DividerLine 설정 패널
 * 토스식 UX: 구분선 스타일 카드 선택 -> 텍스트 설정 -> 고급 설정(접힘)
 */

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 THICKNESS_CARDS = [
  { value: "1px", label: "얇게", size: "1px" },
  { value: "2px", label: "보통", size: "2px" },
  { value: "4px", label: "두껍게", size: "4px" },
] as const;

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

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

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

  const updateConfig = (field: string, 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-3 gap-2">
          {THICKNESS_CARDS.map((card) => {
            const isSelected = (config.thickness || "1px") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("thickness", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-2.5 text-center transition-all min-h-[56px]",
                  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 w-full rounded-full"
                  style={{
                    height: card.size,
                    backgroundColor: config.color || "#d1d5db",
                  }}
                />
                <span className="text-xs font-medium">{card.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 2단계: 선 색상 카드 선택 ─── */}
      <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 = (config.color || "#d1d5db") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("color", 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 className="flex items-center gap-2 pt-1">
          <input
            type="color"
            value={config.color || "#d1d5db"}
            onChange={(e) => updateConfig("color", e.target.value)}
            className="h-7 w-7 cursor-pointer rounded border"
          />
          <Input
            value={config.color || "#d1d5db"}
            onChange={(e) => updateConfig("color", e.target.value)}
            placeholder="#d1d5db"
            className="h-7 flex-1 text-xs"
          />
        </div>
      </div>

      {/* ─── 3단계: 구분선 텍스트 ─── */}
      <div className="space-y-3">
        <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={!!config.dividerText}
            onCheckedChange={(checked) =>
              updateConfig("dividerText", checked ? "구분" : "")
            }
          />
        </div>

        {config.dividerText && (
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">텍스트</span>
              <Input
                value={config.dividerText || ""}
                onChange={(e) => updateConfig("dividerText", e.target.value)}
                placeholder="구분 텍스트 입력"
                className="h-7 w-[160px] text-xs"
              />
            </div>
            <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={config.textColor || "#6b7280"}
                  onChange={(e) => updateConfig("textColor", e.target.value)}
                  className="h-6 w-6 cursor-pointer rounded border"
                />
                <Input
                  value={config.textColor || "#6b7280"}
                  onChange={(e) => updateConfig("textColor", e.target.value)}
                  className="h-7 w-[100px] text-xs"
                />
              </div>
            </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.rounded || false}
                onCheckedChange={(checked) => updateConfig("rounded", 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.disabled || false}
                onCheckedChange={(checked) => updateConfig("disabled", checked)}
              />
            </div>
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2DividerLineConfigPanel.displayName = "V2DividerLineConfigPanel";

export default V2DividerLineConfigPanel;
