/**
 * 日期篩選器元件
 * 支援快捷日期範圍選項和自定義日期範圍
 */

import { Calendar } from "lucide-react";
import { Label } from "../ui/label";
import { Input } from "../ui/input";
import { Button } from "../ui/button";

export interface DateRange {
  start: string; // YYYY-MM-DD 格式
  end: string; // YYYY-MM-DD 格式
}

interface DateFilterProps {
  dateRange: DateRange | null;
  onDateRangeChange: (range: DateRange | null) => void;
}

// 快捷日期選項
const DATE_SHORTCUTS = [
  { label: "今天", getValue: () => getDateRange(0) },
  { label: "最近7天", getValue: () => getDateRange(7) },
  { label: "最近30天", getValue: () => getDateRange(30) },
  { label: "本月", getValue: () => getCurrentMonth() },
  { label: "上月", getValue: () => getLastMonth() },
];

// 獲取從今天往前 N 天的日期範圍
function getDateRange(days: number): DateRange {
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - days);

  return {
    start: formatDate(start),
    end: formatDate(end),
  };
}

// 獲取本月的日期範圍
function getCurrentMonth(): DateRange {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth(), 1);
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);

  return {
    start: formatDate(start),
    end: formatDate(end),
  };
}

// 獲取上月的日期範圍
function getLastMonth(): DateRange {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const end = new Date(now.getFullYear(), now.getMonth(), 0);

  return {
    start: formatDate(start),
    end: formatDate(end),
  };
}

// 格式化日期為 YYYY-MM-DD
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

export function DateFilter({ dateRange, onDateRangeChange }: DateFilterProps) {
  const handleStartDateChange = (value: string) => {
    if (!value) {
      onDateRangeChange(null);
      return;
    }

    onDateRangeChange({
      start: value,
      end: dateRange?.end || value,
    });
  };

  const handleEndDateChange = (value: string) => {
    if (!value) {
      onDateRangeChange(null);
      return;
    }

    onDateRangeChange({
      start: dateRange?.start || value,
      end: value,
    });
  };

  const handleShortcutClick = (getValue: () => DateRange) => {
    onDateRangeChange(getValue());
  };

  const handleClearClick = () => {
    onDateRangeChange(null);
  };

  return (
    <div className="space-y-4">
      {/* 標題 */}
      <div className="flex items-center gap-2">
        <Calendar className="h-4 w-4 text-muted-foreground" />
        <Label>建立日期</Label>
      </div>

      {/* 快捷選項 */}
      <div className="flex flex-wrap gap-2">
        {DATE_SHORTCUTS.map((shortcut) => (
          <Button
            key={shortcut.label}
            variant="outline"
            size="sm"
            onClick={() => handleShortcutClick(shortcut.getValue)}
            className="button-outlined-primary"
          >
            {shortcut.label}
          </Button>
        ))}
      </div>

      {/* 自定義日期範圍 */}
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          {/* 開始日期 */}
          <div className="space-y-2">
            <Label htmlFor="start-date" className="text-sm text-muted-foreground">
              開始日期
            </Label>
            <Input
              id="start-date"
              type="date"
              value={dateRange?.start || ""}
              onChange={(e) => handleStartDateChange(e.target.value)}
              className="border-2"
            />
          </div>

          {/* 結束日期 */}
          <div className="space-y-2">
            <Label htmlFor="end-date" className="text-sm text-muted-foreground">
              結束日期
            </Label>
            <Input
              id="end-date"
              type="date"
              value={dateRange?.end || ""}
              onChange={(e) => handleEndDateChange(e.target.value)}
              className="border-2"
            />
          </div>
        </div>

        {/* 清除按鈕 */}
        {dateRange && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleClearClick}
            className="w-full button-outlined-primary"
          >
            清除日期篩選
          </Button>
        )}
      </div>
    </div>
  );
}
