import { QueryBuilder } from '@mui/icons-material'
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 ITimePicker {
  label?: ReactNode
  name?: string
  required?: boolean
  minTime?: Date | string | number
  maxTime?: Date | string | number
  value: Date | null
  onChange: (value: Date) => void
  placeholder?: string
  inputProps?: TextFieldProps
  size?: 'medium' | 'small'
  disabled?: boolean
}

export default function TimePicker({
  name,
  label,
  required,
  minTime,
  maxTime,
  onChange,
  value,
  placeholder,
  size = 'medium',
  disabled,
  ...rest
}: ITimePicker) {
  return (
    <Flatpickr
      options={{
        enableTime: true,
        noCalendar: true,
        dateFormat: 'h:i K',
        minTime,
        maxTime,
        allowInput: true,
      }}
      onClose={(dates) => {
        if (onChange) onChange(dates[0])
      }}
      onChange={(dates: Date[]) => {
        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}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <QueryBuilder />
                </InputAdornment>
              ),
            }}
            disabled={disabled}
            {...rest.inputProps}
          />
        )
      }}
    />
  )
}
