import { useMemo } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useMutation } from 'react-query';

import ChevronLeft from '@material-hu/icons/material/ChevronLeft';
import Close from '@material-hu/icons/material/Close';
import Drawer from '@material-hu/mui/Drawer';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import { type DrawerProps } from '@material-hu/components/design-system/Drawer/types';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { useRequiredAuth } from 'src/contexts/JWTContext';
import { useLayoutMetrics } from 'src/contexts/LayoutMetricsContext';
import useTopModal from 'src/contexts/TopModalContext';
import ErrorModal from 'src/pages/dashboard/Forms/Form/components/ContentTab/components/ErrorModal';
import * as instancesService from 'src/services/instancesService';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormSelect from 'src/components/FormInputs/FormSelect';

const parseTime = (time: string) =>
  `${time.split(':')[0]}:${time.split(':')[1]}`;

const getHourOptions = () => {
  let options = [];

  for (let i = 0; i < 24; i++) {
    options.push(i < 10 ? `0${i}:00` : `${i}:00`);
    options.push(i < 10 ? `0${i}:30` : `${i}:30`);
  }
  options = options.map(value => ({ value, label: value }));

  return options;
};

type NotificationTimeDrawerProps = DrawerProps & {
  onClose: () => void;
  onGoBack: () => void;
};

const NotificationSettingsDrawer = ({
  onGoBack,
  ...props
}: NotificationTimeDrawerProps) => {
  const { t } = useLokaliseTranslation('apps');
  const { instance, updateInstance } = useRequiredAuth();
  const options = useMemo(getHourOptions, []);
  const { enqueueSnackbar } = useHuSnackbar();
  const { setTopModal } = useTopModal();
  const { navbarHeight } = useLayoutMetrics();
  const { onClose } = props;

  const setNotificationTimeMutation = useMutation(
    ({ notificationBirthdayTime }: { notificationBirthdayTime: string }) =>
      instancesService.setBirthdayNotificationTime(
        instance.id,
        notificationBirthdayTime,
      ),
    {
      onSuccess: (_data, values) => {
        enqueueSnackbar({ title: t('SAVED'), variant: 'success' });
        updateInstance!({
          ...instance,
          birthdayNotificationTime: values.notificationBirthdayTime,
        });
      },
      onError: () => {
        setTopModal(<ErrorModal />);
      },
    },
  );

  const form = useForm({
    defaultValues: {
      notificationBirthdayTime:
        parseTime(instance.birthdayNotificationTime) || '',
    },
  });

  const notificationBirthdayTime = form.watch('notificationBirthdayTime');

  return (
    <Drawer
      anchor="right"
      PaperProps={{
        sx: {
          height: '100%',
          top: navbarHeight,
          maxHeight: `calc(100vh - ${navbarHeight}px)`,
          width: 600,
          borderTopLeftRadius: theme => theme.spacing(2),
        },
      }}
      {...props}
    >
      <Stack
        sx={{
          flexDirection: 'row',
          gap: 1,
          justifyContent: 'space-between',
          aligItems: 'center',
          p: 3,
          pt: 3,
          pb: 2,
          borderBottom: '1px solid',
          borderColor: theme => theme.palette.grey[100],
          alignItems: 'center',
        }}
      >
        <IconButton
          onClick={onGoBack}
          edge="start"
        >
          <ChevronLeft />
        </IconButton>
        <Typography
          variant="h6"
          sx={{ textAlign: 'left', flex: 1 }}
        >
          {t('CONFIG_NOTIFICATIONS')}
        </Typography>
        <IconButton
          onClick={onClose}
          edge="end"
        >
          <Close />
        </IconButton>
      </Stack>
      <FormProvider {...form}>
        <Stack sx={{ height: '100%', flex: 1, p: 3, gap: 2 }}>
          <Typography>{t('SET_TIME_SUBTITLE')}</Typography>
          <Stack
            sx={{
              p: 2,
              pt: 3,
              borderRadius: 2,
              bgcolor: theme => theme.palette.grey[50],
              gap: 2,
            }}
          >
            <FormSelect
              name="notificationBirthdayTime"
              label={t('NOTIFICATIONS_SCHEDULE')}
              options={options}
              formControlProps={{
                sx: { width: '100%' },
              }}
              helperText={t('UTC_TIME')}
              selectProps={{
                sx: {
                  bgcolor: theme => theme.palette.common.white,
                },
              }}
            />
            <Typography variant="body2">
              {t('NOTIFICATIONS_SCHEDULE_DESCRIPTION')}
            </Typography>
          </Stack>
        </Stack>
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 2,
            alignItems: 'center',
            width: '100%',
            px: 3,
            py: 2,
            borderTop: '1px solid',
            borderColor: theme => theme.palette.grey[100],
          }}
        >
          <Button
            onClick={onGoBack}
            fullWidth
          >
            {t('CANCEL')}
          </Button>
          <Button
            onClick={() => {
              setNotificationTimeMutation.mutateAsync({
                notificationBirthdayTime,
              });
              onClose();
            }}
            variant="contained"
            disabled={!notificationBirthdayTime}
            fullWidth
          >
            {t('CONFIRM')}
          </Button>
        </Stack>
      </FormProvider>
    </Drawer>
  );
};

export default NotificationSettingsDrawer;
