"use client";

/**
 * V2Date 설정 패널
 * 토스식 단계별 UX: 날짜 타입 카드 선택 -> 표시 설정 -> 고급 설정(접힘)
 */

import React, { useState, useMemo } from "react";
import { Label } from "@/components/ui/label";
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 { Calendar, Clock, CalendarClock, Settings, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";

// ─── 날짜 타입 카드 정의 ───
const DATE_TYPE_CARDS = [
  {
    value: "date",
    icon: Calendar,
    title: "날짜",
    description: "연/월/일을 선택해요",
  },
  {
    value: "time",
    icon: Clock,
    title: "시간",
    description: "시/분을 선택해요",
  },
  {
    value: "datetime",
    icon: CalendarClock,
    title: "날짜+시간",
    description: "날짜와 시간을 함께 선택해요",
  },
] as const;

// ─── 날짜 타입별 표시 형식 옵션 ───
const FORMAT_OPTIONS: Record<string, { value: string; label: string }[]> = {
  date: [
    { value: "YYYY-MM-DD", label: "YYYY-MM-DD" },
    { value: "YYYY/MM/DD", label: "YYYY/MM/DD" },
    { value: "DD/MM/YYYY", label: "DD/MM/YYYY" },
    { value: "MM/DD/YYYY", label: "MM/DD/YYYY" },
    { value: "YYYY년 MM월 DD일", label: "YYYY년 MM월 DD일" },
  ],
  time: [
    { value: "HH:mm", label: "HH:mm" },
    { value: "HH:mm:ss", label: "HH:mm:ss" },
  ],
  datetime: [
    { value: "YYYY-MM-DD HH:mm", label: "YYYY-MM-DD HH:mm" },
    { value: "YYYY-MM-DD HH:mm:ss", label: "YYYY-MM-DD HH:mm:ss" },
    { value: "YYYY/MM/DD HH:mm", label: "YYYY/MM/DD HH:mm" },
    { value: "YYYY년 MM월 DD일", label: "YYYY년 MM월 DD일" },
  ],
};

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

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

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

  const currentDateType = config.dateType || config.type || "date";
  const showTimeOptions = currentDateType === "datetime" || currentDateType === "time";

  const formatOptions = useMemo(() => {
    return FORMAT_OPTIONS[currentDateType] || FORMAT_OPTIONS.date;
  }, [currentDateType]);

  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">
          {DATE_TYPE_CARDS.map((card) => {
            const Icon = card.icon;
            const isSelected = currentDateType === card.value;
            return (
              <button
                key={card.value}
                type="button"
                onClick={() => updateConfig("dateType", 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단계: 표시 설정 ─── */}
      <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
        <span className="text-sm font-medium">표시 설정</span>

        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">표시 형식</span>
          <Select
            value={config.format || formatOptions[0]?.value || "YYYY-MM-DD"}
            onValueChange={(value) => updateConfig("format", value)}
          >
            <SelectTrigger className="h-8 w-[180px] text-sm">
              <SelectValue placeholder="형식 선택" />
            </SelectTrigger>
            <SelectContent>
              {formatOptions.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex items-center justify-between py-1.5">
          <span className="text-xs text-muted-foreground">안내 텍스트</span>
          <Input
            value={config.placeholder || ""}
            onChange={(e) => updateConfig("placeholder", e.target.value)}
            placeholder="날짜 선택"
            className="h-8 w-[180px] text-sm"
          />
        </div>
      </div>

      {/* ─── 3단계: 옵션 (Switch + 설명) ─── */}
      <div className="space-y-2">
        <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.range || false}
            onCheckedChange={(checked) => updateConfig("range", 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.showToday !== false}
            onCheckedChange={(checked) => updateConfig("showToday", checked)}
          />
        </div>

        {showTimeOptions && (
          <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.showSeconds || false}
              onCheckedChange={(checked) => updateConfig("showSeconds", checked)}
            />
          </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">
            <p className="text-xs text-muted-foreground">
              선택 가능한 날짜 범위를 제한할 수 있어요
            </p>

            <div className="flex gap-2">
              <div className="flex-1">
                <Label className="text-xs text-muted-foreground">최소 날짜</Label>
                <Input
                  type="date"
                  value={config.minDate || ""}
                  onChange={(e) => updateConfig("minDate", e.target.value)}
                  className="h-8 w-full text-sm"
                />
              </div>
              <div className="flex-1">
                <Label className="text-xs text-muted-foreground">최대 날짜</Label>
                <Input
                  type="date"
                  value={config.maxDate || ""}
                  onChange={(e) => updateConfig("maxDate", e.target.value)}
                  className="h-8 w-full text-sm"
                />
              </div>
            </div>

            <p className="text-[11px] text-muted-foreground">
              비워두면 제한 없이 모든 날짜를 선택할 수 있어요
            </p>
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
};

V2DateConfigPanel.displayName = "V2DateConfigPanel";

export default V2DateConfigPanel;
