import React from 'react';
import { DialogActionsProps } from '@mui/material/DialogActions';
import { usePickerContext, usePickerTranslations } from '@mui/x-date-pickers';
import { styled } from '@mui/material/styles';

import { Button, DialogActions } from '@/mui/components';

export type PickersActionBarAction = 'clear' | 'cancel' | 'accept' | 'today' | 'next' | 'nextOrAccept';

export interface PickersActionBarProps extends DialogActionsProps {
  actions?: PickersActionBarAction[];
}

const PickersActionBarRoot = styled(DialogActions, {
  name: 'MuiPickersLayout',
  slot: 'ActionBar',
})({});

function PickersActionBarComponent(props: PickersActionBarProps) {
  const { actions, ...other } = props;

  const translations = usePickerTranslations();
  const { clearValue, setValueToToday, acceptValueChanges, cancelValueChanges, goToNextStep, hasNextStep } =
    usePickerContext();

  if (actions == null || actions.length === 0) {
    return null;
  }

  const buttons = actions?.map((actionType) => {
    switch (actionType) {
      case 'clear':
        return (
          <Button size="small" variant="outlined" onClick={clearValue} key={actionType}>
            {translations.clearButtonLabel}
          </Button>
        );

      case 'cancel':
        return (
          <Button size="small" variant="outlined" onClick={cancelValueChanges} key={actionType}>
            {translations.cancelButtonLabel}
          </Button>
        );

      case 'accept':
        return (
          <Button size="small" variant="contained" onClick={acceptValueChanges} key={actionType}>
            {translations.okButtonLabel}
          </Button>
        );

      case 'today':
        return (
          <Button size="small" variant="contained" onClick={setValueToToday} key={actionType}>
            {translations.todayButtonLabel}
          </Button>
        );

      case 'next':
        return (
          <Button size="small" variant="contained" onClick={goToNextStep} key={actionType}>
            {translations.nextStepButtonLabel}
          </Button>
        );

      case 'nextOrAccept':
        if (hasNextStep) {
          return (
            <Button size="small" variant="contained" onClick={goToNextStep} key={actionType}>
              {translations.nextStepButtonLabel}
            </Button>
          );
        }
        return (
          <Button size="small" variant="contained" onClick={acceptValueChanges} key={actionType}>
            {translations.okButtonLabel}
          </Button>
        );

      default:
        return null;
    }
  });

  return <PickersActionBarRoot {...other}>{buttons}</PickersActionBarRoot>;
}

const PickersActionBar = React.memo(PickersActionBarComponent);

export default PickersActionBar;
