import { useCallback, useState } from 'react';
import { UseMutationOptions } from 'react-query';

import { AxiosError, AxiosResponse } from 'axios';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconPlayerPlay, IconSquare } from '@material-hu/icons/tabler';

import { ClockInParams } from 'src/services/timeTracking';
import { ResponseError } from 'src/types/services';
import { EntryType, UserSite } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import MarkingClockDrawer from '.';

type DrawerProps = {
  lastEntrySite: UserSite | null;
};

type Props = {
  toggleClockMutation: (
    params: ClockInParams,
    options?: UseMutationOptions<
      AxiosResponse,
      AxiosError<ResponseError>,
      ClockInParams
    >,
  ) => void;
  isLoadingToggleClock: boolean;
  entryType: EntryType;
};

export const useMarkingClockDrawer = (props: Props) => {
  const { toggleClockMutation, isLoadingToggleClock, entryType } = props;
  const [selectedSite, setSelectedSite] = useState<UserSite | null>(null);
  const { t } = useLokaliseTranslation([
    'time_tracker',
    'general',
    'regions_sites',
  ]);

  const handleDrawerCloseWithoutSubmit = () => {
    setSelectedSite(
      entryType === EntryType.END && selectedSite ? selectedSite : null,
    );
    closeMarkingClockDrawer();
  };

  const {
    showDrawer: showMarkingClockDrawer,
    drawer,
    closeDrawer: closeMarkingClockDrawer,
  } = useDrawerV2<DrawerProps>(({ lastEntrySite, closeDrawer }) => {
    const PrimaryButtonIcon =
      entryType === EntryType.START ? <IconPlayerPlay /> : <IconSquare />;

    return {
      children: (
        <MarkingClockDrawer
          selectedSite={selectedSite}
          handleSiteSelection={setSelectedSite}
          lastEntrySiteId={lastEntrySite?.id}
          entryType={entryType}
        />
      ),
      title:
        entryType === EntryType.START
          ? t('time_tracker:clock_start')
          : t('time_tracker:clock_end'),
      hasBackButton: true,
      onClose: handleDrawerCloseWithoutSubmit,
      primaryButtonProps: {
        children: t(
          entryType === EntryType.START
            ? 'time_tracker:init'
            : 'time_tracker:stop',
        ),
        startIcon: isLoadingToggleClock ? undefined : PrimaryButtonIcon,
        fullWidth: true,
        onClick: () => {
          if (!selectedSite) return;
          toggleClockMutation(
            {
              type: entryType,
              siteId: selectedSite.id,
              location: selectedSite.location,
            },
            {
              onSuccess: () => {
                setSelectedSite(null);
                closeDrawer();
              },
            },
          );
        },
        disabled: !selectedSite,
        loading: isLoadingToggleClock,
      },
      secondaryButtonProps: {
        children: t('time_tracker:go_back'),
        fullWidth: true,
        onClick: handleDrawerCloseWithoutSubmit,
      },
    };
  });

  const memoizedShowDrawer = useCallback(
    ({ lastEntrySite }: DrawerProps) => {
      setSelectedSite(lastEntrySite ?? null);
      showMarkingClockDrawer({ lastEntrySite });
    },
    [showMarkingClockDrawer],
  );

  return {
    drawer,
    showMarkingClockDrawer: memoizedShowDrawer,
    closeMarkingClockDrawer,
  };
};
