"use client";

/**
 * V2SectionCard 설정 패널
 * 토스식 단계별 UX: 패딩 카드 선택 -> 배경/테두리 설정 -> 고급 설정(접힘)
 */

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
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,
  Square,
  Minus,
  SquareDashed,
} from "lucide-react";
import { cn } from "@/lib/utils";

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

// ─── 배경색 카드 정의 ───
const BG_CARDS = [
  { value: "default", label: "카드", description: "기본 카드 배경" },
  { value: "muted", label: "회색", description: "연한 회색 배경" },
  { value: "transparent", label: "투명", description: "배경 없음" },
] as const;

// ─── 테두리 스타일 카드 정의 ───
const BORDER_CARDS = [
  { value: "solid", label: "실선", icon: Minus },
  { value: "dashed", label: "점선", icon: SquareDashed },
  { value: "none", label: "없음", icon: Square },
] as const;

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

export const V2SectionCardConfigPanel: React.FC<
  V2SectionCardConfigPanelProps
> = ({ 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-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.showHeader !== false}
            onCheckedChange={(checked) => updateConfig("showHeader", checked)}
          />
        </div>

        {config.showHeader !== false && (
          <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.title || ""}
                onChange={(e) => updateConfig("title", e.target.value)}
                placeholder="섹션 제목 입력"
                className="h-7 w-[180px] text-xs"
              />
            </div>
            <div>
              <span className="text-xs text-muted-foreground">설명 (선택)</span>
              <Textarea
                value={config.description || ""}
                onChange={(e) => updateConfig("description", e.target.value)}
                placeholder="섹션에 대한 간단한 설명"
                className="mt-1.5 text-xs resize-none"
                rows={2}
              />
            </div>
          </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-3">
        <p className="text-sm font-medium">외관</p>
        <div className="rounded-lg border bg-muted/30 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">
              {BG_CARDS.map((card) => {
                const isSelected =
                  (config.backgroundColor || "default") === card.value;
                return (
                  <button
                    key={card.value}
                    type="button"
                    onClick={() =>
                      updateConfig("backgroundColor", 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"
                    )}
                  >
                    <span className="text-xs font-medium">{card.label}</span>
                    <span className="text-[10px] text-muted-foreground">
                      {card.description}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* 테두리 스타일 */}
          <div>
            <span className="text-xs text-muted-foreground">테두리</span>
            <div className="mt-1.5 grid grid-cols-3 gap-2">
              {BORDER_CARDS.map((card) => {
                const Icon = card.icon;
                const isSelected =
                  (config.borderStyle || "solid") === card.value;
                return (
                  <button
                    key={card.value}
                    type="button"
                    onClick={() => updateConfig("borderStyle", card.value)}
                    className={cn(
                      "flex flex-col items-center rounded-md border p-2 text-center transition-all gap-1",
                      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-xs font-medium">{card.label}</span>
                  </button>
                );
              })}
            </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.collapsible || false}
                onCheckedChange={(checked) =>
                  updateConfig("collapsible", checked)
                }
              />
            </div>

            {config.collapsible && (
              <div className="ml-4 border-l-2 border-primary/20 pl-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.defaultOpen !== false}
                    onCheckedChange={(checked) =>
                      updateConfig("defaultOpen", checked)
                    }
                  />
                </div>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2SectionCardConfigPanel.displayName = "V2SectionCardConfigPanel";

export default V2SectionCardConfigPanel;
