"use client"

import * as React from "react"
import { format, parse, isValid } from "date-fns"
import { ar, enUS } from "date-fns/locale"
import { CalendarIcon } from "lucide-react"
import { useLocale } from "next-intl"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"

interface DatePickerProps {
  value?: string
  onChange?: (value: string) => void
  placeholder?: string
  className?: string
  disabled?: boolean
  invalid?: boolean
  "aria-label"?: string
  fromYear?: number
  toYear?: number
}

export function DatePicker({
  value,
  onChange,
  placeholder,
  className,
  disabled,
  invalid,
  "aria-label": ariaLabel,
  fromYear,
  toYear,
}: DatePickerProps) {
  const locale = useLocale()
  const isRtl = locale === "ar"
  const dateFnsLocale = isRtl ? ar : enUS

  const selected = value && isValid(parse(value, "yyyy-MM-dd", new Date()))
    ? parse(value, "yyyy-MM-dd", new Date())
    : undefined

  const handleSelect = (date: Date | undefined) => {
    if (date) onChange?.(format(date, "yyyy-MM-dd"))
    else onChange?.("")
  }

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="outline"
          disabled={disabled}
          aria-invalid={invalid}
          aria-label={ariaLabel}
          className={cn(
            "h-10 w-full justify-between rounded-lg border-input bg-background px-3 font-normal text-foreground shadow-xs",
            "hover:bg-accent hover:text-accent-foreground",
            "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
            !selected && "text-muted-foreground",
            invalid &&
              "border-destructive focus-visible:border-destructive focus-visible:ring-destructive/20",
            className
          )}
          dir={isRtl ? "rtl" : "ltr"}
        >
          <span>
            {selected
              ? format(selected, "dd/MM/yyyy", { locale: dateFnsLocale })
              : (placeholder ?? "dd/mm/yyyy")}
          </span>
          <CalendarIcon className="size-4 text-muted-foreground" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="w-auto border-border bg-popover p-0 text-popover-foreground"
        align={isRtl ? "end" : "start"}
      >
        <Calendar
          mode="single"
          selected={selected}
          onSelect={handleSelect}
          locale={dateFnsLocale}
          dir={isRtl ? "rtl" : "ltr"}
          startMonth={fromYear ? new Date(fromYear, 0) : undefined}
          endMonth={toYear ? new Date(toYear, 11) : undefined}
          autoFocus
        />
      </PopoverContent>
    </Popover>
  )
}
