'use client'

import clsx from 'clsx'
import { useLocale } from 'next-intl'
import { type ComponentProps, useState } from 'react'
import { DateRange, DayPicker, type Locale } from 'react-day-picker'
import { ru } from 'react-day-picker/locale'

import { TbChevronDown, TbChevronLeft, TbChevronRight } from 'react-icons/tb'

import { allStyles, mainStyles, type MainStylesProps } from './Calendar.styles'

type CalendarProps = {
	onSelect?: (value: any) => void
	defaultSelected?: DateRange
} & ComponentProps<typeof DayPicker> &
	MainStylesProps

function Calendar({
	mode = 'single',
	size,
	onSelect,
	className,
	defaultSelected
}: CalendarProps) {
	const [selectedDate, setSelectedDate] = useState(defaultSelected)
	//
	const locale = useLocale()
	//
	const localeObj: Record<string, Locale> = { ru }
	//
	const onChangeHandler = (value: any) => {
		setSelectedDate(value)
		if (onSelect) onSelect(value)
	}
	//
	return (
		<DayPicker
			{...(locale !== 'en' && { locale: localeObj[locale] })}
			selected={selectedDate}
			onSelect={onChangeHandler}
			mode={mode as any}
			showOutsideDays
			navLayout='after'
			className={mainStyles({ size, className })}
			classNames={allStyles({ size })}
			components={{
				Root: ({ className, rootRef, ...props }) => {
					return (
						<div ref={rootRef} className={className} {...props} />
					)
				},
				Weekday: ({ children, className, ...props }) => {
					return (
						<th {...props}>
							<button className={className}>{children}</button>
						</th>
					)
				},
				Day: ({ day, modifiers, className, ...props }) => {
					return (
						<td
							className={clsx('group/day', className)}
							{...props}
						/>
					)
				},
				DayButton: ({ day, modifiers, className, ...props }) => {
					return (
						<button
							data-selected-single={
								modifiers.selected &&
								modifiers.range_start &&
								modifiers.range_end
							}
							className={className}
							{...props}
						/>
					)
				},
				Chevron: ({ className, orientation, ...props }) => {
					switch (orientation) {
						case 'left':
							return <TbChevronLeft {...props} />
						case 'right':
							return <TbChevronRight {...props} />
						default:
							return <TbChevronDown {...props} />
					}
				}
			}}
		/>
	)
}

export { Calendar }
