import { useEffect, useMemo, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import {
  type FetchNextPageOptions,
  type InfiniteQueryObserverResult,
} from 'react-query';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconZoomExclamation } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTable from '@material-hu/components/design-system/Table';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';

import { useGetManagerTypes } from 'src/hooks/queryHooks/vacations';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  MassiveApprovalHeader,
  RequestRowContent,
  RequestRowHeader,
  type RequestTableActionsMenu,
} from 'src/pages/dashboard/timeOff/components/requestReport';
import { type Vacations } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  getCheckedForEachCheckbox,
  vacationsTableHeader,
} from 'src/utils/vacations';

import InfiniteTable from 'src/components/InfiniteTable';

import { getRequestDetailsDrawer } from '../Drawers/RequestDetailsDrawer';
import { EmptyState } from '../EmptyState/EmptyState';

export type RequestsTableProps = {
  isManagerView?: boolean;
  vacationData: Vacations;
  countRequest?: number;
  isLoading: boolean;
  fetchNextPage: (
    options?: FetchNextPageOptions,
  ) => Promise<InfiniteQueryObserverResult<unknown, unknown>>;
  hasNextPage: boolean;
  isFetchingNextPage: boolean;
};

const RequestsTable = (props: RequestsTableProps) => {
  const {
    isManagerView = false,
    vacationData,
    countRequest = 0,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = props;
  const HuGoThemeProvider = useHuGoTheme();
  const [selectAllRequests, setSelectAllRequests] = useState(false);
  const [actionsMenu, setActionsMenu] = useState<RequestTableActionsMenu>(null);
  const { t } = useLokaliseTranslation('time_off');
  const { isAdmin } = useGetManagerTypes();

  const form = useForm({
    defaultValues: {
      requests: vacationData.reduce(
        (obj, cur) => ({ ...obj, [cur.id]: false }),
        {},
      ),
    },
  });
  const { watch, setValue } = form;

  const { requests } = watch();

  useEffect(() => {
    setValue(
      'requests',
      vacationData.reduce(
        (obj, cur) =>
          getCheckedForEachCheckbox(
            obj,
            cur,
            requests,
            selectAllRequests,
            isAdmin,
          ),
        {},
      ),
    );
  }, [vacationData.length]);

  const { drawer: requestDetailDrawer, showDrawer: showRequestDetailDrawer } =
    useDrawerV2<{ requestId: number }>(args =>
      getRequestDetailsDrawer({
        ...args,
        isManagerView,
        requestId: args.requestId,
      }),
    );

  const handleOnOpenRequestDetailDrawer = (requestId: number) => {
    showRequestDetailDrawer({ requestId });
  };

  const totalColumns = useMemo(() => {
    const headerColumns = vacationsTableHeader(t, isManagerView).length;
    const checkboxColumn = isManagerView ? 1 : 0;
    const actionsColumn = 1;

    return headerColumns + checkboxColumn + actionsColumn;
  }, [t, isManagerView]);

  return (
    <HuGoThemeProvider>
      {requestDetailDrawer}
      <Stack
        sx={{
          overflow: 'hidden',
        }}
      >
        {!isManagerView && (
          <Stack
            sx={{
              mb: 2,
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
            }}
          >
            <Typography
              variant="globalL"
              sx={{
                fontWeight: 'fontWeightSemiBold',
              }}
            >
              {t('requests_made')}
            </Typography>
          </Stack>
        )}
        <FormProvider {...form}>
          <HuTableContainer>
            {isManagerView && (
              <MassiveApprovalHeader
                vacationData={vacationData}
                countRequest={countRequest}
                onSetSelectAllRequest={setSelectAllRequests}
              />
            )}
            <HuTableContainer
              sx={{
                borderRadius: 0,
                flex: 1,
                overflow: 'auto',
              }}
            >
              <HuTable>
                <RequestRowHeader
                  vacationData={vacationData}
                  isManagerView={isManagerView}
                  onSetSelectAllRequest={setSelectAllRequests}
                />
                <InfiniteTable
                  fetchNextPage={fetchNextPage}
                  hasNextPage={hasNextPage}
                  isFetchingNextPage={isFetchingNextPage}
                  isLoading={isLoading}
                  totalColumns={totalColumns}
                  isEmpty={!vacationData?.length}
                  renderEmptyState={
                    isLoading ? (
                      <HuCircularProgress />
                    ) : (
                      <EmptyState
                        titleProps={{
                          title: isManagerView
                            ? t('no_agent_requests')
                            : t('no_registered_requests'),
                          description: isManagerView
                            ? t('follow_up_agent_requests')
                            : t('follow_up_requests'),
                        }}
                        Icon={IconZoomExclamation}
                      />
                    )
                  }
                >
                  {vacationData?.map(item => (
                    <RequestRowContent
                      key={item?.id}
                      vacations={item}
                      isManagerView={isManagerView}
                      onSetSelectAllRequest={setSelectAllRequests}
                      onOpenRequestDetailDrawer={
                        handleOnOpenRequestDetailDrawer
                      }
                      actionsMenu={actionsMenu}
                      onOpenActionsMenu={requestId =>
                        setActionsMenu({ requestId })
                      }
                      onCloseActionsMenu={() => setActionsMenu(null)}
                    />
                  ))}
                </InfiniteTable>
              </HuTable>
            </HuTableContainer>
          </HuTableContainer>
        </FormProvider>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default RequestsTable;
