"use client";

/**
 * V2Layout 설정 패널
 * 토스식 단계별 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 {
  LayoutGrid,
  PanelLeftClose,
  MoveHorizontal,
  Minus,
  MonitorPlay,
  Settings,
  ChevronDown,
} from "lucide-react";
import { cn } from "@/lib/utils";

// ─── 레이아웃 타입 카드 정의 ───
const LAYOUT_TYPE_CARDS = [
  {
    value: "grid",
    icon: LayoutGrid,
    title: "그리드",
    description: "행과 열로 배치해요",
  },
  {
    value: "split",
    icon: PanelLeftClose,
    title: "분할 패널",
    description: "영역을 나눠서 배치해요",
  },
  {
    value: "flex",
    icon: MoveHorizontal,
    title: "플렉스",
    description: "유연하게 배치해요",
  },
  {
    value: "divider",
    icon: Minus,
    title: "구분선",
    description: "영역을 구분해요",
  },
  {
    value: "screen-embed",
    icon: MonitorPlay,
    title: "화면 임베드",
    description: "다른 화면을 불러와요",
  },
] as const;

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

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

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

  const currentLayoutType = config.layoutType || config.type || "grid";
  const isGridType = currentLayoutType === "grid";
  const isSplitType = currentLayoutType === "split";
  const isFlexType = currentLayoutType === "flex";
  const isScreenEmbedType = currentLayoutType === "screen-embed";

  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">
          {LAYOUT_TYPE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = currentLayoutType === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("layoutType", card.value)}
                className={cn(
                  "flex flex-col items-center justify-center rounded-lg border p-3 text-center transition-all min-h-[80px]",
                  isSelected
                    ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                    : "border-border hover:border-primary/50 hover:bg-muted/50",
                )}
              >
                <Icon className="h-5 w-5 mb-1.5 text-primary" />
                <span className="text-xs font-medium leading-tight">
                  {card.title}
                </span>
                <span className="text-[10px] text-muted-foreground leading-tight mt-0.5">
                  {card.description}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ─── 2단계: 타입별 설정 ─── */}

      {/* 그리드 타입 설정 */}
      {isGridType && (
        <div className="space-y-3">
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <LayoutGrid className="h-4 w-4 text-primary" />
              <span className="text-sm font-medium">그리드 설정</span>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">컬럼 수</span>
              <Select
                value={String(config.columns || 12)}
                onValueChange={(value) => updateConfig("columns", Number(value))}
              >
                <SelectTrigger className="h-8 w-[180px] text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">1 컬럼</SelectItem>
                  <SelectItem value="2">2 컬럼</SelectItem>
                  <SelectItem value="3">3 컬럼</SelectItem>
                  <SelectItem value="4">4 컬럼</SelectItem>
                  <SelectItem value="6">6 컬럼</SelectItem>
                  <SelectItem value="12">12 컬럼</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">간격 (px)</span>
              <Input
                value={config.gap || "16"}
                onChange={(e) => updateConfig("gap", e.target.value)}
                placeholder="16"
                className="h-8 w-[180px] text-sm"
              />
            </div>
          </div>

          <div className="flex items-center justify-between py-1">
            <div>
              <p className="text-sm">12컬럼 그리드</p>
              <p className="text-[11px] text-muted-foreground">
                표준 12컬럼 그리드 시스템을 사용해요
              </p>
            </div>
            <Switch
              checked={config.use12Column !== false}
              onCheckedChange={(checked) => updateConfig("use12Column", checked)}
            />
          </div>
        </div>
      )}

      {/* 분할 패널 타입 설정 */}
      {isSplitType && (
        <div className="space-y-3">
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <PanelLeftClose className="h-4 w-4 text-primary" />
              <span className="text-sm font-medium">분할 설정</span>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">분할 방향</span>
              <Select
                value={config.direction || "horizontal"}
                onValueChange={(value) => updateConfig("direction", value)}
              >
                <SelectTrigger className="h-8 w-[180px] text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="horizontal">가로</SelectItem>
                  <SelectItem value="vertical">세로</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex gap-2">
              <div className="flex-1">
                <span className="text-xs text-muted-foreground">비율 (%)</span>
                <Input
                  type="number"
                  value={config.splitRatio?.[0] || 50}
                  onChange={(e) => updateConfig("splitRatio", [Number(e.target.value), 100 - Number(e.target.value)])}
                  placeholder="50"
                  min="10"
                  max="90"
                  className="mt-1 h-8 text-sm"
                />
              </div>
              <div className="flex-1">
                <span className="text-xs text-muted-foreground">나머지</span>
                <Input
                  type="number"
                  value={config.splitRatio?.[1] || 50}
                  disabled
                  className="mt-1 h-8 text-sm bg-muted"
                />
              </div>
            </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.resizable !== false}
              onCheckedChange={(checked) => updateConfig("resizable", checked)}
            />
          </div>
        </div>
      )}

      {/* 플렉스 타입 설정 */}
      {isFlexType && (
        <div className="space-y-3">
          <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
            <div className="flex items-center gap-2">
              <MoveHorizontal className="h-4 w-4 text-primary" />
              <span className="text-sm font-medium">플렉스 설정</span>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">방향</span>
              <Select
                value={config.direction || "row"}
                onValueChange={(value) => updateConfig("direction", value)}
              >
                <SelectTrigger className="h-8 w-[180px] text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="row">가로</SelectItem>
                  <SelectItem value="column">세로</SelectItem>
                  <SelectItem value="row-reverse">가로 (역순)</SelectItem>
                  <SelectItem value="column-reverse">세로 (역순)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">정렬</span>
              <Select
                value={config.justifyContent || "flex-start"}
                onValueChange={(value) => updateConfig("justifyContent", value)}
              >
                <SelectTrigger className="h-8 w-[180px] text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="flex-start">시작</SelectItem>
                  <SelectItem value="center">가운데</SelectItem>
                  <SelectItem value="flex-end">끝</SelectItem>
                  <SelectItem value="space-between">양끝 정렬</SelectItem>
                  <SelectItem value="space-around">균등 배치</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">교차축 정렬</span>
              <Select
                value={config.alignItems || "stretch"}
                onValueChange={(value) => updateConfig("alignItems", value)}
              >
                <SelectTrigger className="h-8 w-[180px] text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="flex-start">시작</SelectItem>
                  <SelectItem value="center">가운데</SelectItem>
                  <SelectItem value="flex-end">끝</SelectItem>
                  <SelectItem value="stretch">늘리기</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center justify-between py-1.5">
              <span className="text-xs text-muted-foreground">간격 (px)</span>
              <Input
                value={config.gap || "16"}
                onChange={(e) => updateConfig("gap", e.target.value)}
                placeholder="16"
                className="h-8 w-[180px] text-sm"
              />
            </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.wrap || false}
              onCheckedChange={(checked) => updateConfig("wrap", checked)}
            />
          </div>
        </div>
      )}

      {/* 화면 임베드 타입 설정 */}
      {isScreenEmbedType && (
        <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <MonitorPlay className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">임베드 설정</span>
          </div>

          <div className="flex items-center justify-between py-1.5">
            <span className="text-xs text-muted-foreground">화면 ID</span>
            <Input
              type="number"
              value={config.screenId || ""}
              onChange={(e) => updateConfig("screenId", e.target.value ? Number(e.target.value) : undefined)}
              placeholder="화면 ID 입력"
              className="h-8 w-[180px] text-sm"
            />
          </div>
        </div>
      )}

      {/* 구분선 타입: 별도 설정 없음 - 빈 상태 표시 */}
      {currentLayoutType === "divider" && (
        <div className="text-center py-6 text-muted-foreground">
          <Minus className="mx-auto mb-2 h-8 w-8 opacity-30" />
          <p className="text-sm">추가 설정이 없어요</p>
          <p className="text-xs mt-0.5">구분선은 기본 스타일로 표시돼요</p>
        </div>
      )}

      {/* ─── 3단계: 고급 설정 (그리드/플렉스 타입에서만) ─── */}
      {(isGridType || isFlexType || isSplitType) && (
        <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">
              {isGridType && (
                <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.responsive !== false}
                    onCheckedChange={(checked) => updateConfig("responsive", checked)}
                  />
                </div>
              )}

              {isFlexType && (
                <div className="flex items-center justify-between py-1.5">
                  <span className="text-xs text-muted-foreground">최소 아이템 너비</span>
                  <Input
                    value={config.minItemWidth || ""}
                    onChange={(e) => updateConfig("minItemWidth", e.target.value)}
                    placeholder="자동"
                    className="h-8 w-[180px] text-sm"
                  />
                </div>
              )}

              {isSplitType && (
                <div className="flex items-center justify-between py-1.5">
                  <span className="text-xs text-muted-foreground">최소 패널 크기 (px)</span>
                  <Input
                    type="number"
                    value={config.minPanelSize || ""}
                    onChange={(e) => updateConfig("minPanelSize", e.target.value ? Number(e.target.value) : undefined)}
                    placeholder="자동"
                    className="h-8 w-[180px] text-sm"
                  />
                </div>
              )}
            </div>
          </CollapsibleContent>
        </Collapsible>
      )}
    </div>
  );
};

V2LayoutConfigPanel.displayName = "V2LayoutConfigPanel";

export default V2LayoutConfigPanel;
