"use client"

import * as React from "react"
import type { DropdownProps } from "react-day-picker"
import { DayPicker } from "react-day-picker"

import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

import "react-day-picker/style.css"

export type CalendarProps = React.ComponentProps<typeof DayPicker>

type OptionElement = React.ReactElement<{
  value: string | number
  children: React.ReactNode
  disabled?: boolean
}>

type CalendarDropdownProps = DropdownProps & { children?: React.ReactNode }

const TODAY_HIGHLIGHT_CLASS = [
  // Subtle cyan background + ring when today isn't selected
  "[&_button]:ring-1 [&_button]:ring-[#00d6eb] [&_button]:ring-offset-1 [&_button]:ring-offset-white",
  "[&_button:not([aria-selected='true'])]:bg-[#00e8ff]/20 [&_button:not([aria-selected='true'])]:text-neutral-900",
  // Preserve selection colors but keep a cyan outline when today is part of the range
  "[&_button[aria-selected='true']]:ring-[#00f5ff] [&_button[aria-selected='true']]:ring-offset-neutral-900 [&_button[aria-selected='true']]:shadow-[0_0_0_1.5px_rgba(0,214,235,0.45)]",
].join(" ")

const buildOptions = (options?: DropdownProps["options"], children?: React.ReactNode) => {
  if (options && options.length > 0) {
    return options.map((option) => ({
      value: option.value,
      label: option.label,
      disabled: option.disabled,
    }))
  }

  return React.Children.toArray(children)
    .filter((child): child is OptionElement => React.isValidElement(child))
    .map((child) => ({
      value: child.props.value,
      label: child.props.children,
      disabled: child.props.disabled ?? false,
    }))
}

function CalendarDropdown(props: CalendarDropdownProps) {
  const { value, onChange, options: optionProp, children } = props
  const disabled = props.disabled
  const ariaLabel = props["aria-label"]

  const options = React.useMemo(() => buildOptions(optionProp, children), [optionProp, children])
  const stringValue = value !== undefined && value !== null ? String(value) : ""

  const handleChange = (next: string) => {
    const match = options.find((option) => String(option.value) === next)
    const payload = match ? match.value : next
    onChange?.({
      target: { value: payload },
    } as React.ChangeEvent<HTMLSelectElement>)
  }

  const isYearDropdown = options.every((option) => String(option.value).length === 4)
  const triggerWidth = isYearDropdown ? "w-[96px]" : "w-[108px]"

  const displayText = React.useMemo(() => {
    if (!options.length) return ""
    const selected = options.find((o) => String(o.value) === stringValue)
    if (!selected) return ""
    if (isYearDropdown) return String(selected.label)
    const label = String(selected.label)
    const abbr = label.slice(0, 3)
    return abbr.charAt(0).toUpperCase() + abbr.slice(1).toLowerCase()
  }, [options, stringValue, isYearDropdown])

  return (
    <Select value={stringValue} onValueChange={handleChange} disabled={disabled}>
      <SelectTrigger
        aria-label={ariaLabel}
        className={cn(
          "h-8 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700 shadow-none transition hover:bg-slate-50 focus-visible:ring-2 focus-visible:ring-neutral-900/10 disabled:cursor-not-allowed disabled:opacity-60",
          triggerWidth
        )}
      >
        {/* Mostra mês abreviado no trigger; lista usa label completo */}
        <span className="truncate">
          {displayText}
        </span>
      </SelectTrigger>
      <SelectContent
        align="start"
        className="max-h-72 min-w-[var(--radix-select-trigger-width)] rounded-2xl border border-[#00e8ff]/20 bg-white/95 text-neutral-800 shadow-[0_10px_40px_-10px_rgba(0,155,177,0.25)] backdrop-blur-sm"
      >
        {options.map((option) => (
          <SelectItem
            key={String(option.value)}
            value={String(option.value)}
            disabled={option.disabled}
            className="rounded-lg text-sm font-medium text-neutral-700 focus:bg-slate-100 focus:text-neutral-900"
          >
            {option.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}

export function Calendar({
  className,
  classNames,
  styles,
  modifiersClassNames,
  showOutsideDays = true,
  captionLayout = "dropdown",
  startMonth,
  endMonth,
  ...props
}: CalendarProps) {
  const mergedStyles = React.useMemo(
    () => ({
      day_selected: { backgroundColor: "transparent" },
      day_range_start: { backgroundColor: "transparent" },
      day_range_end: { backgroundColor: "transparent" },
      day_range_middle: { backgroundColor: "transparent" },
      ...(styles ?? {}),
    }),
    [styles]
  )

  return (
    <DayPicker
      showOutsideDays={showOutsideDays}
      captionLayout={captionLayout}
      startMonth={startMonth}
      endMonth={endMonth}
      styles={mergedStyles}
      className={cn(
        "mx-auto flex w-[320px] flex-col gap-3 rounded-2xl bg-transparent p-4 text-neutral-900 shadow-none",
        className
      )}
      classNames={{
        months: "flex flex-col items-center gap-4",
        // Layout em grid de 3 colunas para posicionar setas à esquerda/direita
        month: "grid grid-cols-[auto_1fr_auto] items-center gap-x-2 gap-y-3",
        month_caption: "col-start-2 col-end-3 flex items-center justify-center gap-2 px-0",
        dropdowns: "flex items-center gap-2",
        nav: "flex items-center gap-1",
        button_previous: cn(
          buttonVariants({ variant: "ghost", size: "icon" }),
          "col-start-1 row-start-1 size-8 rounded-full border border-transparent text-neutral-500 hover:border-slate-200 hover:bg-slate-50 hover:text-neutral-900 focus-visible:ring-2 focus-visible:ring-neutral-900/10"
        ),
        button_next: cn(
          buttonVariants({ variant: "ghost", size: "icon" }),
          "col-start-3 row-start-1 size-8 rounded-full border border-transparent text-neutral-500 hover:border-slate-200 hover:bg-slate-50 hover:text-neutral-900 focus-visible:ring-2 focus-visible:ring-neutral-900/10"
        ),
        chevron: "size-4",
        month_grid: "col-span-3 w-full border-collapse",
        weekdays: "grid grid-cols-7 text-[0.7rem] font-medium capitalize text-muted-foreground",
        weekday: "flex h-8 items-center justify-center",
        week: "grid grid-cols-7 gap-1",
        day: "relative flex h-9 items-center justify-center text-sm focus-within:relative focus-within:z-20",
        day_button: cn(
          buttonVariants({ variant: "ghost" }),
          "size-9 rounded-full font-medium text-neutral-700 transition hover:bg-slate-100 hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0 aria-selected:bg-neutral-900 aria-selected:text-neutral-50"
        ),
        // Hoje: estilos principais irão no botão via modifiersClassNames
        today: "text-neutral-900",
        outside: "text-muted-foreground opacity-40",
        disabled: "text-muted-foreground opacity-30 line-through",
        hidden: "invisible",
        ...classNames,
      }}
      modifiersClassNames={{
        range_middle: "bg-transparent text-neutral-900 [&_button]:rounded-full [&_button]:bg-neutral-900/10 [&_button]:text-neutral-900",
        range_start: "bg-transparent [&_button]:rounded-full [&_button]:bg-neutral-900 [&_button]:text-neutral-50 [&_button]:focus-visible:ring-0",
        range_end: "bg-transparent [&_button]:rounded-full [&_button]:bg-neutral-900 [&_button]:text-neutral-50 [&_button]:focus-visible:ring-0",
        today: TODAY_HIGHLIGHT_CLASS,
        ...modifiersClassNames,
      }}
      // Setas ao lado do caption
      navLayout="around"
      components={{
        Dropdown: CalendarDropdown,
        // Tornar os botões de navegação estáticos para encaixar no grid
        PreviousMonthButton: (props) => {
          const { className, children, style, ...rest } = props
          return (
            <button
              type="button"
              {...rest}
              className={className}
              style={{ ...(style || {}), position: "static" }}
            >
              {children}
            </button>
          )
        },
        NextMonthButton: (props) => {
          const { className, children, style, ...rest } = props
          return (
            <button
              type="button"
              {...rest}
              className={className}
              style={{ ...(style || {}), position: "static" }}
            >
              {children}
            </button>
          )
        },
      }}
      {...props}
    />
  )
}
