import * as React from "react"
import {
  ChevronDownIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"

import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"

/**
 * Render a themed DayPicker calendar with custom styling, formatters, and component overrides.
 *
 * @param buttonVariant - Button variant to apply to the month navigation buttons.
 * @returns A DayPicker React element configured with the library's default class names, merged classNames/formatters, and custom component overrides (Root, Chevron, DayButton, WeekNumber).
 */
function Calendar({
  className,
  classNames,
  showOutsideDays = true,
  captionLayout = "label",
  buttonVariant = "ghost",
  formatters,
  components,
  ...props
}: React.ComponentProps<typeof DayPicker> & {
  buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
  const defaultClassNames = getDefaultClassNames()

  return (
    <DayPicker
      showOutsideDays={showOutsideDays}
      className={cn(
        "smx-bg-background smx-group/calendar smx-p-3 [--cell-size:smx-2rem] [[data-slot=card-content]_&]:smx-bg-transparent [[data-slot=popover-content]_&]:smx-bg-transparent",
        String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
        String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
        className
      )}
      captionLayout={captionLayout}
      formatters={{
        formatMonthDropdown: (date) =>
          date.toLocaleString("default", { month: "short" }),
        ...formatters,
      }}
      classNames={{
        root: cn("smx-w-fit", defaultClassNames.root),
        months: cn(
          "smx-relative smx-flex smx-flex-col smx-gap-4 md:smx-flex-row",
          defaultClassNames.months
        ),
        month: cn("smx-flex smx-w-full smx-flex-col smx-gap-4", defaultClassNames.month),
        nav: cn(
          "smx-absolute smx-inset-x-0 smx-top-0 smx-flex smx-w-full smx-items-center smx-justify-between smx-gap-1",
          defaultClassNames.nav
        ),
        button_previous: cn(
          buttonVariants({ variant: buttonVariant }),
          "smx-h-[--cell-size] smx-w-[--cell-size] smx-select-none smx-p-0 aria-disabled:smx-opacity-50",
          defaultClassNames.button_previous
        ),
        button_next: cn(
          buttonVariants({ variant: buttonVariant }),
          "smx-h-[--cell-size] smx-w-[--cell-size] smx-select-none smx-p-0 aria-disabled:smx-opacity-50",
          defaultClassNames.button_next
        ),
        month_caption: cn(
          "smx-flex smx-h-[--cell-size] smx-w-full smx-items-center smx-justify-center smx-px-[--cell-size]",
          defaultClassNames.month_caption
        ),
        dropdowns: cn(
          "smx-flex smx-h-[--cell-size] smx-w-full smx-items-center smx-justify-center smx-gap-1.5 smx-text-sm smx-font-medium",
          defaultClassNames.dropdowns
        ),
        dropdown_root: cn(
          "has-focus:smx-border-ring smx-border-input smx-shadow-xs has-focus:smx-ring-ring/50 has-focus:smx-ring-[3px] smx-relative smx-rounded-md smx-border",
          defaultClassNames.dropdown_root
        ),
        dropdown: cn(
          "smx-bg-popover smx-absolute smx-inset-0 smx-opacity-0",
          defaultClassNames.dropdown
        ),
        caption_label: cn(
          "smx-select-none smx-font-medium",
          captionLayout === "label"
            ? "smx-text-sm"
            : "[&>svg]:smx-text-muted-foreground smx-flex smx-h-8 smx-items-center smx-gap-1 smx-rounded-md smx-pl-2 smx-pr-1 smx-text-sm [&>svg]:smx-size-3.5",
          defaultClassNames.caption_label
        ),
        table: "smx-w-full smx-border-collapse",
        weekdays: cn("smx-flex", defaultClassNames.weekdays),
        weekday: cn(
          "smx-text-muted-foreground smx-flex-1 smx-select-none smx-rounded-md smx-text-[0.8rem] smx-font-normal",
          defaultClassNames.weekday
        ),
        week: cn("smx-mt-2 smx-flex smx-w-full", defaultClassNames.week),
        week_number_header: cn(
          "smx-w-[--cell-size] smx-select-none",
          defaultClassNames.week_number_header
        ),
        week_number: cn(
          "smx-text-muted-foreground smx-select-none smx-text-[0.8rem]",
          defaultClassNames.week_number
        ),
        day: cn(
          "smx-group/day smx-relative smx-aspect-square smx-h-full smx-w-full smx-select-none smx-p-0 smx-text-center [&:first-child[data-selected=true]_button]:smx-rounded-l-md [&:last-child[data-selected=true]_button]:smx-rounded-r-md",
          defaultClassNames.day
        ),
        range_start: cn(
          "smx-bg-accent smx-rounded-l-md",
          defaultClassNames.range_start
        ),
        range_middle: cn("smx-rounded-none", defaultClassNames.range_middle),
        range_end: cn("smx-bg-accent smx-rounded-r-md", defaultClassNames.range_end),
        today: cn(
          "smx-bg-accent smx-text-accent-foreground smx-rounded-md data-[selected=true]:smx-rounded-none",
          defaultClassNames.today
        ),
        outside: cn(
          "smx-text-muted-foreground aria-selected:smx-text-muted-foreground",
          defaultClassNames.outside
        ),
        disabled: cn(
          "smx-text-muted-foreground smx-opacity-50",
          defaultClassNames.disabled
        ),
        hidden: cn("smx-invisible", defaultClassNames.hidden),
        ...classNames,
      }}
      components={{
        Root: ({ className, rootRef, ...props }) => {
          return (
            <div
              data-slot="calendar"
              ref={rootRef}
              className={cn(className)}
              {...props}
            />
          )
        },
        Chevron: ({ className, orientation, ...props }) => {
          if (orientation === "left") {
            return (
              <ChevronLeftIcon className={cn("smx-size-4", className)} {...props} />
            )
          }

          if (orientation === "right") {
            return (
              <ChevronRightIcon
                className={cn("smx-size-4", className)}
                {...props}
              />
            )
          }

          return (
            <ChevronDownIcon className={cn("smx-size-4", className)} {...props} />
          )
        },
        DayButton: CalendarDayButton,
        WeekNumber: ({ children, ...props }) => {
          return (
            <td {...props}>
              <div className="smx-flex smx-size-[--cell-size] smx-items-center smx-justify-center smx-text-center">
                {children}
              </div>
            </td>
          )
        },
        ...components,
      }}
      {...props}
    />
  )
}

/**
 * Render a calendar day as a themed Button with selection/range state attributes and automatic focus when appropriate.
 *
 * The component maps day and modifiers to a Button with:
 * - data-day set to the day's localized date string
 * - data-selected-single when a single date is selected (not a range)
 * - data-range-start, data-range-end, data-range-middle for range states
 * It also focuses the underlying button when `modifiers.focused` becomes true.
 *
 * @param className - Additional CSS class names to merge with internal day styling
 * @param day - The `day` object provided by react-day-picker representing the cell's date
 * @param modifiers - Modifier flags from react-day-picker (e.g., `selected`, `range_start`, `range_end`, `range_middle`, `focused`)
 * @returns The Button element used to render a single day cell
 */
function CalendarDayButton({
  className,
  day,
  modifiers,
  ...props
}: React.ComponentProps<typeof DayButton>) {
  const defaultClassNames = getDefaultClassNames()

  const ref = React.useRef<HTMLButtonElement>(null)
  React.useEffect(() => {
    if (modifiers.focused) ref.current?.focus()
  }, [modifiers.focused])

  return (
    <Button
      ref={ref}
      variant="ghost"
      size="icon"
      data-day={day.date.toLocaleDateString()}
      data-selected-single={
        modifiers.selected &&
        !modifiers.range_start &&
        !modifiers.range_end &&
        !modifiers.range_middle
      }
      data-range-start={modifiers.range_start}
      data-range-end={modifiers.range_end}
      data-range-middle={modifiers.range_middle}
      className={cn(
        "data-[selected-single=true]:smx-bg-primary data-[selected-single=true]:smx-text-primary-foreground data-[range-middle=true]:smx-bg-accent data-[range-middle=true]:smx-text-accent-foreground data-[range-start=true]:smx-bg-primary data-[range-start=true]:smx-text-primary-foreground data-[range-end=true]:smx-bg-primary data-[range-end=true]:smx-text-primary-foreground smx-group-data-[focused=true]/day:border-ring smx-group-data-[focused=true]/day:ring-ring smx-flex smx-aspect-square smx-h-auto smx-w-full smx-min-w-[--cell-size] smx-flex-col smx-gap-1 smx-font-normal smx-leading-none data-[range-end=true]:smx-rounded-md data-[range-middle=true]:smx-rounded-none data-[range-start=true]:smx-rounded-md smx-group-data-[focused=true]/day:relative smx-group-data-[focused=true]/day:z-10 smx-group-data-[focused=true]/day:ring-[3px] [&>span]:smx-text-xs [&>span]:smx-opacity-70",
        defaultClassNames.day,
        className
      )}
      {...props}
    />
  )
}

export { Calendar, CalendarDayButton }