import { useState } from 'react';

import {
  IconEdit,
  IconInfoCircle,
  IconPlus,
  IconTrash,
} from '@material-hu/icons/tabler';
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 CardContainer from '@material-hu/components/design-system/CardContainer';
import Search from '@material-hu/components/design-system/Inputs/Search';
import Skeleton from '@material-hu/components/design-system/Skeleton';
import useSnackbar from '@material-hu/components/design-system/Snackbar';
import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { useDebounce } from 'src/hooks/useDebounce';
import { type Shift } from 'src/types/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';

import EmptyState from 'src/components/HuEmptyState';
import { InfiniteList } from 'src/components/list';
import TemplateCard from './TemplateCard';
import { useGetShiftsRepository } from '../../hooks/useGetShiftsRepository';
import { useDeleteShiftTemplateMutation } from '../../hooks/useDeleteShiftTemplateMutation';

type Props = {
  onCreate: () => void;
  onEdit: (shift: Shift) => void;
};

const IndividualShiftsTab = ({ onCreate, onEdit }: Props) => {
  const [search, setSearch] = useState('');
  const { debouncedValue: debouncedSearch } = useDebounce(search, 300);
  const { t } = useLokaliseTranslation('shifts');
  const { enqueueSnackbar } = useSnackbar();
  const { openDialog, closeDialog } = useDialogLayer();

  const {
    registers,
    isLoading: isLoadingShiftsRepository,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useGetShiftsRepository({ search: debouncedSearch });

  const {
    mutate: deleteShiftTemplateMutation,
    isLoading: isDeletingShiftTemplate,
  } = useDeleteShiftTemplateMutation();

  const confirmDeleteShift = (shift: Shift) => {
    openDialog({
      title: t('actions.delete_shift.title'),
      textBody: t('actions.delete_shift.description'),
      onClose: () => closeDialog(),
      primaryButtonProps: {
        children: t('general:delete'),
        onClick: () => {
          closeDialog();
          deleteShiftTemplateMutation(shift.id, {
            onSuccess: () => {
              enqueueSnackbar({
                title: `${t('actions.delete_shift.success')} ${shift.name}`,
                variant: 'success',
              });
            },
          });
        },
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: () => closeDialog(),
      },
      dialogProps: { fullWidth: true, maxWidth: 'sm' },
    });
  };

  const shiftMenuOptions = (shift: Shift) => [
    {
      Icon: IconEdit,
      title: t('edit_shift'),
      onClick: () => onEdit(shift),
    },
    {
      Icon: IconTrash,
      title: t('delete_shift'),
      onClick: () => confirmDeleteShift(shift),
    },
  ];

  const resultsFetched = !!registers?.length;

  return (
    <Stack sx={{ gap: 2, flex: 1, minHeight: 0 }}>
      <Typography
        variant="globalL"
        sx={{
          fontWeight: 'fontWeightSemiBold',
        }}
      >
        {t('created_shifts')}
      </Typography>
      <Stack
        sx={{
          flexDirection: 'row',
          gap: 1,
          alignItems: 'center',
        }}
      >
        <Stack sx={{ flex: 1 }}>
          <Search
            value={search}
            placeholder={t('search_by_name')}
            onChange={inputValue => {
              setSearch(inputValue);
            }}
          />
        </Stack>
        <Button
          variant="primary"
          color="primary"
          startIcon={<IconPlus size={16} />}
          onClick={onCreate}
        >
          {t('create_shift')}
        </Button>
      </Stack>

      <CardContainer
        sx={{
          overflowY: 'auto',
          flex: 1,
        }}
        fullWidth
      >
        {!resultsFetched && !isLoadingShiftsRepository && (
          <EmptyState
            titleProps={{
              title: t('no_shifts_saved_yet'),
              description: t('no_shifts_saved_yet_description'),
            }}
            avatarProps={{
              Icon: IconInfoCircle,
              color: 'highlight',
            }}
            buttonProps={{
              text: t('create_shift'),
              onClick: onCreate,
            }}
            sx={{ backgroundColor: 'transparent' }}
          />
        )}
        {(resultsFetched || isLoadingShiftsRepository) && (
          <InfiniteList
            isSuccess={resultsFetched}
            isLoading={isLoadingShiftsRepository}
            isFetchingNextPage={isFetchingNextPage}
            hasNextPage={hasNextPage}
            fetchNextPage={fetchNextPage}
            renderSkeleton={
              <Stack sx={{ gap: 1 }}>
                <Skeleton height={58} />
                <Skeleton height={58} />
                <Skeleton height={58} />
                <Skeleton height={58} />
              </Stack>
            }
            sx={{
              display: 'flex',
              flexDirection: 'column',
              gap: 2,
            }}
            loadingSkeleton
          >
            {registers?.map(register => (
              <TemplateCard
                key={register.id}
                shift={register}
                isDeletingShiftTemplate={isDeletingShiftTemplate}
                getCardOptions={shiftMenuOptions}
              />
            ))}
          </InfiniteList>
        )}
      </CardContainer>
    </Stack>
  );
};

export default IndividualShiftsTab;
