import { FC } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

import CloseIcon from '@material-hu/icons/material/Close';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import { DesktopDatePicker } from '@material-hu/mui/x-date-pickers/DesktopDatePicker';

export type DesktopDatePickerControlProps = {
  label: string;
  name: string;
  withDeleteOption?: boolean;
  defaultValue?: any;
};

export const DesktopDatePickerControl: FC<
  DesktopDatePickerControlProps
> = props => {
  const { label, name, withDeleteOption = false, defaultValue = null } = props;

  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultValue}
      render={({ field }) => (
        <Box sx={{ display: 'flex', alignItems: 'center', mx: 2 }}>
          <DesktopDatePicker
            label={label}
            value={field.value}
            onChange={newValue => field.onChange(newValue)}
            maxDate={new Date()}
            slotProps={{
              textField: {
                sx: {
                  '& .MuiInputBase-root': {
                    borderRadius: '4px',
                  },
                  '& input': {
                    paddingTop: '12px',
                    paddingBottom: '12px',
                    fontSize: '14px',
                    width: '180px',
                  },
                  '& label': {
                    top: '-4px',
                  },
                  '& svg': {
                    width: '20px',
                    height: '20px',
                  },
                },
              },
            }}
          />
          {withDeleteOption && (
            <IconButton
              sx={{ ml: 0.5 }}
              onClick={() => field.onChange(null)}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          )}
        </Box>
      )}
    />
  );
};

export default DesktopDatePickerControl;
