"use client";

/**
 * V2TextDisplay 설정 패널
 * 토스식 단계별 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,
  AlignLeft,
  AlignCenter,
  AlignRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { TextDisplayConfig } from "@/lib/registry/components/v2-text-display/types";

const FONT_SIZE_CARDS = [
  { value: "12px", label: "작게", preview: "Aa" },
  { value: "14px", label: "보통", preview: "Aa" },
  { value: "18px", label: "크게", preview: "Aa" },
  { value: "24px", label: "제목", preview: "Aa" },
] as const;

const FONT_WEIGHT_CARDS = [
  { value: "lighter", label: "얇게" },
  { value: "normal", label: "보통" },
  { value: "bold", label: "굵게" },
] as const;

const ALIGN_CARDS = [
  { value: "left", label: "왼쪽", icon: AlignLeft },
  { value: "center", label: "가운데", icon: AlignCenter },
  { value: "right", label: "오른쪽", icon: AlignRight },
] as const;

interface V2TextDisplayConfigPanelProps {
  config: TextDisplayConfig;
  onChange: (config: Partial<TextDisplayConfig>) => void;
}

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

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

    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>
        <Input
          value={config.text || ""}
          onChange={(e) => updateConfig("text", e.target.value)}
          placeholder="표시할 텍스트를 입력하세요"
          className="h-8 text-sm"
        />
        <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-4 gap-2">
          {FONT_SIZE_CARDS.map((card) => {
            const isSelected = (config.fontSize || "14px") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("fontSize", 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="font-medium"
                  style={{ fontSize: card.value }}
                >
                  {card.preview}
                </span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  {card.label}
                </span>
              </button>
            );
          })}
        </div>
        <div className="flex items-center justify-between pt-1">
          <span className="text-[11px] text-muted-foreground">직접 입력</span>
          <Input
            value={config.fontSize || "14px"}
            onChange={(e) => updateConfig("fontSize", e.target.value)}
            placeholder="14px"
            className="h-7 w-[100px] text-xs"
          />
        </div>
      </div>

      {/* ─── 3단계: 폰트 굵기 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">폰트 굵기</p>
        <div className="grid grid-cols-3 gap-2">
          {FONT_WEIGHT_CARDS.map((card) => {
            const isSelected = (config.fontWeight || "normal") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("fontWeight", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-2.5 text-center transition-all min-h-[50px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <span
                  className="text-sm"
                  style={{ fontWeight: card.value }}
                >
                  가나다
                </span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  {card.label}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 4단계: 텍스트 정렬 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">텍스트 정렬</p>
        <div className="grid grid-cols-3 gap-2">
          {ALIGN_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = (config.textAlign || "left") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("textAlign", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-2.5 text-center transition-all gap-1 min-h-[50px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50"
                )}
              >
                <Icon className="h-4 w-4 text-muted-foreground" />
                <span className="text-[10px] text-muted-foreground">
                  {card.label}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 5단계: 텍스트 색상 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">텍스트 색상</p>
        <div className="rounded-lg border bg-muted/30 p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div
                className="h-6 w-6 rounded-md border"
                style={{ backgroundColor: config.color || "#212121" }}
              />
              <span className="text-xs text-muted-foreground">
                {config.color || "#212121"}
              </span>
            </div>
            <Input
              type="color"
              value={config.color || "#212121"}
              onChange={(e) => updateConfig("color", e.target.value)}
              className="h-7 w-[60px] cursor-pointer p-0.5"
            />
          </div>
        </div>
      </div>

      {/* ─── 6단계: 고급 설정 (기본 접혀있음) ─── */}
      <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-2">
                <div
                  className="h-5 w-5 rounded border"
                  style={{ backgroundColor: config.backgroundColor || "#ffffff" }}
                />
                <Input
                  type="color"
                  value={config.backgroundColor || "#ffffff"}
                  onChange={(e) => updateConfig("backgroundColor", e.target.value)}
                  className="h-7 w-[60px] cursor-pointer p-0.5"
                />
              </div>
            </div>

            {/* 패딩 */}
            <div className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">패딩</span>
              <Input
                value={config.padding || ""}
                onChange={(e) => updateConfig("padding", e.target.value)}
                placeholder="8px"
                className="h-7 w-[100px] text-xs"
              />
            </div>

            {/* 모서리 둥글기 */}
            <div className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">모서리 둥글기</span>
              <Input
                value={config.borderRadius || ""}
                onChange={(e) => updateConfig("borderRadius", e.target.value)}
                placeholder="4px"
                className="h-7 w-[100px] text-xs"
              />
            </div>

            {/* 테두리 */}
            <div className="flex items-center justify-between py-1">
              <span className="text-xs text-muted-foreground">테두리</span>
              <Input
                value={config.border || ""}
                onChange={(e) => updateConfig("border", e.target.value)}
                placeholder="1px solid #d1d5db"
                className="h-7 w-[140px] text-xs"
              />
            </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>
  );
};

V2TextDisplayConfigPanel.displayName = "V2TextDisplayConfigPanel";

export default V2TextDisplayConfigPanel;
