"use client"

import { cn } from "@/lib/utils"
import {
  type Locale,
  locales,
  getStartOfWeek,
  getEndOfWeek,
  getStartOfMonth,
  getEndOfMonth,
  addDays,
  addMonths,
} from "@/lib/date-utils"
import { Button } from "@/components/ui/button"

export interface DateRange {
  start: Date
  end: Date
}

interface PresetShortcutsProps {
  onSelect: (range: DateRange) => void
  locale: Locale
  className?: string
}

export function PresetShortcuts({ onSelect, locale, className }: PresetShortcutsProps) {
  const config = locales[locale]
  const isRTL = config.direction === "rtl"
  const today = new Date()

  const presets = [
    {
      label: config.today,
      getRange: (): DateRange => ({ start: today, end: today }),
    },
    {
      label: config.thisWeek,
      getRange: (): DateRange => ({
        start: getStartOfWeek(today),
        end: getEndOfWeek(today),
      }),
    },
    {
      label: config.lastWeek,
      getRange: (): DateRange => {
        const lastWeek = addDays(today, -7)
        return {
          start: getStartOfWeek(lastWeek),
          end: getEndOfWeek(lastWeek),
        }
      },
    },
    {
      label: config.thisMonth,
      getRange: (): DateRange => ({
        start: getStartOfMonth(today),
        end: getEndOfMonth(today),
      }),
    },
    {
      label: config.lastMonth,
      getRange: (): DateRange => {
        const lastMonth = addMonths(today, -1)
        return {
          start: getStartOfMonth(lastMonth),
          end: getEndOfMonth(lastMonth),
        }
      },
    },
    {
      label: config.last3Months,
      getRange: (): DateRange => ({
        start: addMonths(today, -3),
        end: today,
      }),
    },
    {
      label: config.last7Days,
      getRange: (): DateRange => ({
        start: addDays(today, -7),
        end: today,
      }),
    },
    {
      label: config.last30Days,
      getRange: (): DateRange => ({
        start: addDays(today, -30),
        end: today,
      }),
    },
    {
      label: config.last90Days,
      getRange: (): DateRange => ({
        start: addDays(today, -90),
        end: today,
      }),
    },
  ]

  return (
    <div
      className={cn("flex flex-col gap-1.5", className)}
      dir={isRTL ? "rtl" : "ltr"}
      role="group"
      aria-label={config.shortcuts}
    >
      <h3 className="mb-1 text-sm font-semibold ">{config.shortcuts}</h3>
      {presets.map((preset, index) => (
        <Button
          key={index}
          variant="ghost"
          size="sm"
          className={cn(
            "h-9 w-full justify-start rounded-md px-3 text-sm font-normal ",
            isRTL && "text-right",
          )}
          onClick={() => onSelect(preset.getRange())}
        >
          {preset.label}
        </Button>
      ))}
    </div>
  )
}
