import EventIcon from '@mui/icons-material/Event'
import {
  InputAdornment,
  TextFieldProps,
  dialogActionsClasses,
} from '@mui/material'
import 'flatpickr/dist/flatpickr.css'
import { ReactNode } from 'react'
import Flatpickr, { DateTimePickerProps } from 'react-flatpickr'
import monthSelectPlugin from 'flatpickr/dist/plugins/monthSelect'
import TextField from './TextField'

export interface IDatePicker {
  label?: ReactNode
  name?: string
  control?: any
  minDate?: Date | string | number
  maxDate?: Date | string | number
  required?: boolean
  value: Date | null
  onChange: (value: Date) => void
  placeholder?: string
  inputProps?: TextFieldProps
  size?: 'medium' | 'small'
  monthSelect?: boolean
  disabled?: boolean
}

const plugins = [
  monthSelectPlugin({
    shorthand: true, //defaults to false
    dateFormat: 'm.y', //defaults to "F Y"
    altFormat: 'F Y', //defaults to "F Y"
  }),
]

export default function FormDatePicker({
  name,
  label,
  minDate,
  maxDate,
  value,
  onChange,
  placeholder,
  size = 'medium',
  required = false,
  monthSelect,
  disabled,
  ...rest
}: IDatePicker) {
  return (
    <Flatpickr
      options={{
        dateFormat: 'd-m-Y',
        minDate,
        maxDate,
        allowInput: true,
      }}
      onChange={(dates: Date[]) => {
        if (onChange) onChange(dates[0])
      }}
      onClose={(dates) => {
        if (onChange) onChange(dates[0])
      }}
      value={value || null}
      render={(
        props: Omit<DateTimePickerProps, 'options' | 'render'>,
        ref: (node: HTMLInputElement | null) => void,
      ) => {
        return (
          <TextField
            size={size}
            placeholder={placeholder}
            label={label}
            name={name}
            variant="outlined"
            autoComplete="off"
            required={required}
            inputRef={ref}
            disabled={disabled}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <EventIcon />
                </InputAdornment>
              ),
            }}
            {...rest.inputProps}
          />
        )
      }}
    />
  )
}
