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

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

export default function DateTimePicker({
  name,
  label,
  required,
  minDate,
  maxDate,
  minTime,
  maxTime,
  onChange,
  value,
  placeholder,
  enableTime = true,
  disabled,
  size = 'medium',
  ...rest
}: IDateTimePicker) {
  return (
    <Flatpickr
      options={{
        enableTime,
        dateFormat: enableTime ? 'd-m-Y h:i K' : 'd-m-Y',
        minDate,
        maxDate,
        minTime,
        maxTime,
        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}
          />
        )
      }}
    />
  )
}
