import { Box, BoxProps, FormHelperText, styled, SvgIcon } from '@mui/material'
import { ReactNode, useEffect, useState } from 'react'
import { DateRangeIcon } from '../IconButtons'
import DateTimePicker from './DateTimePicker'
import FormLabel from './FormLabel'

const StyledDateRangePicker = styled(Box)<{ size: 'small' | 'medium' }>(
  ({ theme, size }) => ({
    borderRadius: '10px',
    height: '50px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    border: theme.borders.grayLight,
    '& .MuiOutlinedInput-notchedOutline': {
      display: 'none',
    },
    '& .MuiSvgIcon-root': {
      margin: '0 20px',
      marginTop: '8px',
    },
    ...(size === 'small' && {
      borderRadius: '5px',
      height: '40px',
      '& .MuiSvgIcon-root': {
        margin: '0 20px',
        marginTop: '8px',
      },
    }),
  }),
)

interface IDateRangePickerProps {
  value: {
    start: Date
    end: Date
  }
  onChange: (value: { start: Date; end: Date }) => void
  enableTime?: boolean
  size?: 'small' | 'medium'
  containerProps?: BoxProps
  label?: ReactNode
  required?: boolean
  name?: string
  error?: boolean
  helperText?: string
  startMinDate?: Date | string | number
  startMaxDate?: Date | string | number
  endMinDate?: Date | string | number
  endMaxDate?: Date | string | number
}
export default function DateRangePicker({
  value,
  onChange,
  enableTime = false,
  size = 'medium',
  containerProps,
  required,
  error,
  helperText,
  label,
  name,
  startMinDate,
  startMaxDate,
  endMinDate,
  endMaxDate,
}: IDateRangePickerProps) {
  const [state, setState] = useState({
    start: null,
    end: null,
  })

  useEffect(() => {
    setState(value)
  }, [value])

  return (
    <Box width={'100%'} {...containerProps}>
      <FormLabel
        required={required}
        name={name ?? 'date-range-picker'}
        label={label}
      />
      <StyledDateRangePicker size={size}>
        <DateTimePicker
          placeholder="From Date"
          value={state.start}
          onChange={(value) => {
            setState((prev) => ({ ...prev, start: value }))
            onChange({ ...state, start: value })
          }}
          enableTime={enableTime}
          inputProps={{ InputProps: null, size: size }}
          minDate={startMinDate}
          maxDate={startMaxDate}
        />
        <SvgIcon>
          <DateRangeIcon />
        </SvgIcon>
        <DateTimePicker
          placeholder="To Date"
          enableTime={enableTime}
          value={state.end}
          onChange={(value) => {
            setState((prev) => ({ ...prev, end: value }))
            onChange({ ...state, end: value })
          }}
          inputProps={{ InputProps: null, size: size }}
          minDate={endMinDate}
          maxDate={endMaxDate}
        />
      </StyledDateRangePicker>
      <>{error && <FormHelperText>{helperText}</FormHelperText>}</>
    </Box>
  )
}
