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

import { merge } from 'lodash-es';
import { useTheme } from '@material-hu/mui/styles';
import { type ExportedUseDesktopPickerSlotProps } from '@material-hu/mui/x-date-pickers/internals/hooks/useDesktopPicker';
import {
  TimePicker,
  type TimePickerProps,
} from '@material-hu/mui/x-date-pickers/TimePicker';

import { simpleDateStringToLocalDate } from 'src/utils/timeUtils';

type Props = {
  textFieldProps?: ExportedUseDesktopPickerSlotProps<
    Date,
    any,
    boolean
  >['textField'];
  timePickerProps?: Partial<TimePickerProps<Date>>;
  name: string;
  validateRules?: any;
  label?: string;
  disablePicker?: boolean;
  hideError?: boolean;
  // Temporary overrides to keep the look and feel of HuGo in DS2 components
  altPrimaryColor?: string;
  altDarkColor?: string;
};

function FormTimePicker({
  timePickerProps,
  textFieldProps,
  name,
  validateRules,
  label = '',
  disablePicker = false,
  hideError = false,
  altPrimaryColor = undefined,
  altDarkColor = undefined,
}: Props) {
  const { control } = useFormContext();

  const theme = useTheme();

  // These are overrides to have color consistency between DS2 and HuGo themes
  const primaryColor = altPrimaryColor || theme.palette.primary.main;
  const secondaryColor = altDarkColor || theme.palette.primary.dark;

  const baseTextFieldProps = {
    label,
    InputLabelProps: { shrink: true },
    variant: 'filled' as const,
    sx: {
      '& .MuiFilledInput-root': {
        backgroundColor: theme.palette.background.default,
        borderColor: theme.palette.grey[400],
        '&:hover': {
          backgroundColor: theme.palette.background.default,
          borderColor: theme.palette.text.primary,
        },
        '&.Mui-focused': {
          backgroundColor: theme.palette.background.default,
          borderColor: primaryColor,
        },
        '&.Mui-error': {
          borderColor: theme.palette.error.main,
        },
      },
      '.MuiInputLabel-root': {
        '&.Mui-focused': {
          color: primaryColor,
        },
      },
      '&.MuiFormControl-root': {
        backgroundColor: 'transparent',
      },
    },
  };

  return (
    <Controller
      render={({ field, fieldState: { error } }) => (
        <TimePicker
          {...timePickerProps}
          {...field}
          slotProps={{
            textField: {
              ...merge(baseTextFieldProps, textFieldProps),
              error: !!error,
              helperText:
                (!hideError && error?.message) ||
                // biome-ignore lint/suspicious/noExplicitAny: <Fix types>
                (textFieldProps as any)?.helperText ||
                '',
              // Added in order to prevent drag and drop invalid values on the time textfield by accident
              onDrop: event => {
                event.preventDefault();
              },
            },
            popper: {
              sx: {
                '.MuiButtonBase-root.Mui-selected': {
                  backgroundColor: primaryColor,
                  ':hover': {
                    backgroundColor: secondaryColor,
                  },
                },
                '.MuiDialogActions-root .MuiButtonBase-root': {
                  color: primaryColor,
                },
              },
            },
          }}
          value={
            typeof field.value === 'string'
              ? simpleDateStringToLocalDate(field.value)
              : field.value
          }
          disableOpenPicker={disablePicker}
          ampm={false}
        />
      )}
      name={name}
      control={control}
      rules={{ validate: validateRules }}
    />
  );
}

export default FormTimePicker;
