"use client";

import { useMemo, useState } from "react";
import { format } from "date-fns";
import { CalendarClock } from "lucide-react";
import {
  DateTimePicker,
  getDefaultFormat,
  type DateTimePickerMode,
} from "@/components/common/shadcn-enhanced";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";

type DemoCase = {
  id: string;
  title: string;
  description: string;
  mode: DateTimePickerMode;
  props?: Partial<React.ComponentProps<typeof DateTimePicker>>;
};

const BASE_CASES: DemoCase[] = [
  {
    id: "year",
    title: "年选择器",
    description: "mode=\"year\"，翻页选择年份",
    mode: "year",
  },
  {
    id: "month",
    title: "年月选择器",
    description: "mode=\"month\"，选择年份 + 月份",
    mode: "month",
  },
  {
    id: "date",
    title: "年月日选择器",
    description: "mode=\"date\"，日历选择年月日（Trial 开始/结束日期使用此模式）",
    mode: "date",
    props: { showToday: true },
  },
  {
    id: "datetime-hour",
    title: "年月日 + 小时",
    description: "mode=\"datetime-hour\"",
    mode: "datetime-hour",
  },
  {
    id: "datetime-minute",
    title: "年月日 + 时分",
    description: "mode=\"datetime-minute\"",
    mode: "datetime-minute",
  },
  {
    id: "datetime-second",
    title: "年月日 + 时分秒",
    description: "mode=\"datetime-second\"",
    mode: "datetime-second",
  },
];

const VARIANT_CASES: DemoCase[] = [
  {
    id: "clearable",
    title: "可清空",
    description: "clearable=true",
    mode: "date",
    props: { clearable: true, showToday: true },
  },
  {
    id: "required",
    title: "必填",
    description: "required=true，不可清空",
    mode: "date",
    props: { required: true, showToday: true },
  },
  {
    id: "disabled",
    title: "禁用",
    description: "disabled=true",
    mode: "date",
    props: { disabled: true, defaultValue: new Date(2026, 2, 15) },
  },
  {
    id: "readonly",
    title: "只读",
    description: "readOnly=true",
    mode: "date",
    props: { readOnly: true, defaultValue: new Date(2026, 2, 15) },
  },
  {
    id: "range",
    title: "日期范围限制",
    description: "minDate / maxDate 限制可选范围",
    mode: "date",
    props: {
      minDate: new Date(2026, 0, 1),
      maxDate: new Date(2026, 11, 31),
      showToday: true,
      clearable: true,
    },
  },
  {
    id: "confirm",
    title: "确认后提交",
    description: "showConfirm=true，需点击「确定」才生效",
    mode: "datetime-minute",
    props: { showConfirm: true, showNow: true, clearable: true },
  },
  {
    id: "12hour",
    title: "12 小时制",
    description: "use12Hour=true",
    mode: "datetime-minute",
    props: { use12Hour: true, clearable: true },
  },
  {
    id: "steps",
    title: "步进选择",
    description: "hourStep=2 / minuteStep=15 / secondStep=10",
    mode: "datetime-second",
    props: { hourStep: 2, minuteStep: 15, secondStep: 10, clearable: true },
  },
];

function formatValue(value: Date | null, mode: DateTimePickerMode) {
  if (!value) return "null";
  return format(value, getDefaultFormat(mode));
}

function DateTimePickerCase({ demo }: { demo: DemoCase }) {
  const [value, setValue] = useState<Date | null>(demo.props?.defaultValue ?? null);

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-base">{demo.title}</CardTitle>
        <CardDescription>{demo.description}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        <DateTimePicker
          mode={demo.mode}
          value={value}
          onChange={setValue}
          placeholder={`请选择${demo.title}`}
          className="max-w-sm"
          {...demo.props}
        />
        <p className="text-xs text-muted-foreground">
          当前值：
          <code className="ml-1 rounded bg-muted px-1.5 py-0.5 text-foreground">
            {formatValue(value, demo.mode)}
          </code>
        </p>
      </CardContent>
    </Card>
  );
}

export default function DateTimePickerDemoPage() {
  const [trialStart, setTrialStart] = useState<Date | null>(new Date(2026, 2, 1));
  const [trialEnd, setTrialEnd] = useState<Date | null>(new Date(2026, 8, 30));

  const trialPreview = useMemo(
    () => ({
      startDate: formatValue(trialStart, "date"),
      endDate: formatValue(trialEnd, "date"),
    }),
    [trialEnd, trialStart]
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <div className="rounded-xl bg-gradient-to-br from-sky-500 to-blue-600 p-2.5">
          <CalendarClock className="h-5 w-5 text-white" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">
            DateTimePicker 时间组件
          </h2>
          <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">
            基于 shadcn Calendar + Popover + Select 封装，覆盖年 / 月 / 日 / 时分秒等场景
          </p>
        </div>
      </div>

      <Card className="border-sky-200 bg-sky-50/40 dark:border-sky-900 dark:bg-sky-950/20">
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Trial 试验 · 年月日集成示例</CardTitle>
          <CardDescription>
            新增 Trial 时「开始日期 / 结束日期」已改用 DateTimePicker mode=&quot;date&quot;，提交格式为 yyyy-MM-dd
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-4 md:grid-cols-2">
          <div className="space-y-2">
            <p className="text-sm font-medium text-slate-700 dark:text-slate-200">开始日期</p>
            <DateTimePicker
              mode="date"
              value={trialStart}
              onChange={setTrialStart}
              placeholder="请选择开始日期"
              showToday
              clearable
            />
          </div>
          <div className="space-y-2">
            <p className="text-sm font-medium text-slate-700 dark:text-slate-200">结束日期</p>
            <DateTimePicker
              mode="date"
              value={trialEnd}
              onChange={setTrialEnd}
              placeholder="请选择结束日期"
              showToday
              clearable
              minDate={trialStart ?? undefined}
            />
          </div>
          <p className="md:col-span-2 text-xs text-muted-foreground">
            模拟提交 payload：
            <code className="ml-1 rounded bg-background px-1.5 py-0.5">
              {`{ startDate: "${trialPreview.startDate}", endDate: "${trialPreview.endDate}" }`}
            </code>
          </p>
        </CardContent>
      </Card>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-50">基础模式</h3>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {BASE_CASES.map((demo) => (
            <DateTimePickerCase key={demo.id} demo={demo} />
          ))}
        </div>
      </section>

      <section className="space-y-3">
        <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-50">交互与边界场景</h3>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {VARIANT_CASES.map((demo) => (
            <DateTimePickerCase key={demo.id} demo={demo} />
          ))}
        </div>
      </section>

      <p className={cn("text-xs text-muted-foreground")}>
        组件路径：@/components/common/shadcn-enhanced/date-time-picker
      </p>
    </div>
  );
}
