"use client";

/**
 * V2SectionPaper 설정 패널
 * 토스식 단계별 UX: 배경색 카드 선택 -> 여백/모서리 카드 선택 -> 고급 설정(접힘)
 */

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Settings, ChevronDown, Palette } from "lucide-react";
import { cn } from "@/lib/utils";

// ─── 배경색 카드 정의 ───
const BG_CARDS = [
  { value: "default", label: "기본", description: "연한 회색" },
  { value: "muted", label: "회색", description: "조금 더 진한" },
  { value: "accent", label: "강조", description: "연한 파랑" },
  { value: "primary", label: "브랜드", description: "브랜드 컬러" },
  { value: "custom", label: "커스텀", description: "직접 선택" },
] as const;

// ─── 내부 여백 카드 정의 ───
const PADDING_CARDS = [
  { value: "none", label: "없음", size: "0px" },
  { value: "sm", label: "작게", size: "12px" },
  { value: "md", label: "중간", size: "16px" },
  { value: "lg", label: "크게", size: "24px" },
] as const;

// ─── 둥근 모서리 카드 정의 ───
const ROUNDED_CARDS = [
  { value: "none", label: "없음", size: "0px" },
  { value: "sm", label: "작게", size: "2px" },
  { value: "md", label: "중간", size: "6px" },
  { value: "lg", label: "크게", size: "8px" },
] as const;

// ─── 그림자 카드 정의 ───
const SHADOW_CARDS = [
  { value: "none", label: "없음" },
  { value: "sm", label: "작게" },
  { value: "md", label: "중간" },
] as const;

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

export const V2SectionPaperConfigPanel: React.FC<
  V2SectionPaperConfigPanelProps
> = ({ 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 },
        })
      );
    }
  };

  const selectedBg = config.backgroundColor || "default";

  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">
          {BG_CARDS.map((card) => {
            const isSelected = selectedBg === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("backgroundColor", 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"
                )}
              >
                {card.value === "custom" ? (
                  <Palette className="h-4 w-4 mb-0.5 text-muted-foreground" />
                ) : null}
                <span className="text-xs font-medium">{card.label}</span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  {card.description}
                </span>
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-muted-foreground">
          색종이 컨셉의 배경색을 선택해요
        </p>
      </div>

      {/* 커스텀 색상 선택 */}
      {selectedBg === "custom" && (
        <div className="rounded-lg border bg-muted/30 p-4">
          <div className="flex items-center justify-between">
            <span className="text-xs text-muted-foreground">커스텀 색상</span>
            <Input
              type="color"
              value={config.customColor || "#f0f0f0"}
              onChange={(e) => updateConfig("customColor", e.target.value)}
              className="h-8 w-[80px] cursor-pointer"
            />
          </div>
        </div>
      )}

      {/* ─── 2단계: 내부 여백 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">내부 여백</p>
        <div className="grid grid-cols-4 gap-2">
          {PADDING_CARDS.map((card) => {
            const isSelected = (config.padding || "md") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("padding", 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.size}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 3단계: 모서리 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">둥근 모서리</p>
        <div className="grid grid-cols-4 gap-2">
          {ROUNDED_CARDS.map((card) => {
            const isSelected =
              (config.roundedCorners || "md") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("roundedCorners", 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.size}
                </span>
              </button>
            );
          })}
        </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>
              <span className="text-xs text-muted-foreground">그림자</span>
              <div className="mt-1.5 grid grid-cols-3 gap-2">
                {SHADOW_CARDS.map((card) => {
                  const isSelected =
                    (config.shadow || "none") === card.value;
                  return (
                    <button
                      key={card.value}
                      type="button"
                      onClick={() => updateConfig("shadow", card.value)}
                      className={cn(
                        "flex items-center justify-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"
                      )}
                    >
                      <span className="text-xs font-medium">{card.label}</span>
                    </button>
                  );
                })}
              </div>
            </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.showBorder || false}
                onCheckedChange={(checked) =>
                  updateConfig("showBorder", checked)
                }
              />
            </div>

            {/* 테두리 스타일 */}
            {config.showBorder && (
              <div className="flex items-center justify-between py-1">
                <span className="text-xs text-muted-foreground">테두리 스타일</span>
                <Select
                  value={config.borderStyle || "subtle"}
                  onValueChange={(value) => updateConfig("borderStyle", value)}
                >
                  <SelectTrigger className="h-7 w-[100px] text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">없음</SelectItem>
                    <SelectItem value="subtle">은은하게</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2SectionPaperConfigPanel.displayName = "V2SectionPaperConfigPanel";

export default V2SectionPaperConfigPanel;
