"use client";

/**
 * V2FileUpload 설정 패널
 * 토스식 단계별 UX: 파일 형식(카드선택) -> 제한 설정 -> 동작/표시(Switch) -> 고급 설정(접힘)
 */

import React, { useState, useMemo, useCallback } 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,
  FileText,
  Image,
  Archive,
  File,
  FileImage,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { FileUploadConfig } from "@/lib/registry/components/v2-file-upload/types";
import { V2FileUploadDefaultConfig } from "@/lib/registry/components/v2-file-upload/config";

const FILE_TYPE_CARDS = [
  { value: "*/*", label: "모든 파일", icon: File, desc: "제한 없음" },
  { value: "image/*", label: "이미지", icon: Image, desc: "JPG, PNG 등" },
  { value: ".pdf,.doc,.docx,.xls,.xlsx", label: "문서", icon: FileText, desc: "PDF, Word, Excel" },
  { value: "image/*,.pdf", label: "이미지+PDF", icon: FileImage, desc: "이미지와 PDF" },
  { value: ".zip,.rar,.7z", label: "압축 파일", icon: Archive, desc: "ZIP, RAR 등" },
] as const;

const VARIANT_CARDS = [
  { value: "default", label: "기본", desc: "기본 스타일" },
  { value: "outlined", label: "테두리", desc: "테두리 강조" },
  { value: "filled", label: "채움", desc: "배경 채움" },
] as const;

const SIZE_CARDS = [
  { value: "sm", label: "작게" },
  { value: "md", label: "보통" },
  { value: "lg", label: "크게" },
] as const;

interface V2FileUploadConfigPanelProps {
  config: FileUploadConfig;
  onChange: (config: Partial<FileUploadConfig>) => void;
  screenTableName?: string;
}

export const V2FileUploadConfigPanel: React.FC<V2FileUploadConfigPanelProps> = ({
  config: propConfig,
  onChange,
  screenTableName,
}) => {
  const [advancedOpen, setAdvancedOpen] = useState(false);

  const config = useMemo(() => ({
    ...V2FileUploadDefaultConfig,
    ...propConfig,
  }), [propConfig]);

  const maxSizeMB = useMemo(() => {
    return (config.maxSize || 10 * 1024 * 1024) / (1024 * 1024);
  }, [config.maxSize]);

  const updateConfig = useCallback(<K extends keyof FileUploadConfig>(
    field: K,
    value: FileUploadConfig[K]
  ) => {
    const newConfig = { ...config, [field]: value };
    onChange({ [field]: value });

    if (typeof window !== "undefined") {
      window.dispatchEvent(
        new CustomEvent("componentConfigChanged", {
          detail: { config: newConfig },
        })
      );
    }
  }, [config, onChange]);

  const handleMaxSizeChange = useCallback((value: string) => {
    const mb = parseFloat(value) || 10;
    updateConfig("maxSize", mb * 1024 * 1024);
  }, [updateConfig]);

  return (
    <div className="space-y-4">
      {/* ─── 1단계: 허용 파일 형식 카드 선택 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">허용 파일 형식</p>
        <div className="grid grid-cols-2 gap-2">
          {FILE_TYPE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = (config.accept || "*/*") === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("accept", card.value)}
                className={cn(
                  "flex items-center gap-2 rounded-lg border p-2.5 text-left transition-all",
                  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 shrink-0 text-muted-foreground" />
                <div className="min-w-0">
                  <span className="text-xs font-medium block">{card.label}</span>
                  <span className="text-[10px] text-muted-foreground block">
                    {card.desc}
                  </span>
                </div>
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-muted-foreground">업로드 가능한 파일 유형을 선택해요</p>
      </div>

      {/* ─── 2단계: 파일 제한 설정 ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">파일 제한</p>
        <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.placeholder || ""}
              onChange={(e) => updateConfig("placeholder", e.target.value)}
              placeholder="파일을 선택하세요"
              className="h-7 w-[160px] text-xs"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <span className="text-xs text-muted-foreground">최대 크기 (MB)</span>
              <Input
                type="number"
                min={1}
                max={100}
                value={maxSizeMB}
                onChange={(e) => handleMaxSizeChange(e.target.value)}
                className="mt-1 h-7 text-xs"
              />
            </div>
            <div>
              <span className="text-xs text-muted-foreground">최대 파일 수</span>
              <Input
                type="number"
                min={1}
                max={50}
                value={config.maxFiles || 10}
                onChange={(e) => updateConfig("maxFiles", parseInt(e.target.value) || 10)}
                className="mt-1 h-7 text-xs"
              />
            </div>
          </div>
        </div>
      </div>

      {/* ─── 3단계: 동작 설정 (Switch) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">동작 설정</p>
        <div className="rounded-lg border bg-muted/30 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.multiple !== false}
              onCheckedChange={(checked) => updateConfig("multiple", 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.allowDelete !== false}
              onCheckedChange={(checked) => updateConfig("allowDelete", 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.allowDownload !== false}
              onCheckedChange={(checked) => updateConfig("allowDownload", checked)}
            />
          </div>
        </div>
      </div>

      {/* ─── 4단계: 표시 설정 (Switch) ─── */}
      <div className="space-y-2">
        <p className="text-sm font-medium">표시 설정</p>
        <div className="rounded-lg border bg-muted/30 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.showPreview !== false}
              onCheckedChange={(checked) => updateConfig("showPreview", 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.showFileList !== false}
              onCheckedChange={(checked) => updateConfig("showFileList", 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.showFileSize !== false}
              onCheckedChange={(checked) => updateConfig("showFileSize", checked)}
            />
          </div>
        </div>
      </div>

      {/* ─── 5단계: 스타일 카드 선택 ─── */}
      <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">
              {VARIANT_CARDS.map((card) => {
                const isSelected = (config.variant || "default") === card.value;
                return (
                  <button
                    key={card.value}
                    type="button"
                    onClick={() => updateConfig("variant", card.value as "default" | "outlined" | "filled")}
                    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.desc}</span>
                  </button>
                );
              })}
            </div>
          </div>
          <div>
            <span className="text-xs text-muted-foreground">크기</span>
            <div className="mt-1.5 grid grid-cols-3 gap-2">
              {SIZE_CARDS.map((card) => {
                const isSelected = (config.size || "md") === card.value;
                return (
                  <button
                    key={card.value}
                    type="button"
                    onClick={() => updateConfig("size", card.value as "sm" | "md" | "lg")}
                    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>
      </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>
              <Input
                value={config.helperText || ""}
                onChange={(e) => updateConfig("helperText", e.target.value)}
                placeholder="안내 문구 입력"
                className="h-7 w-[160px] 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.required || false}
                onCheckedChange={(checked) => updateConfig("required", 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.readonly || false}
                onCheckedChange={(checked) => updateConfig("readonly", 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>
  );
};

V2FileUploadConfigPanel.displayName = "V2FileUploadConfigPanel";

export default V2FileUploadConfigPanel;
