import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconZoomExclamation } from '@material-hu/icons/tabler';
import Container from '@material-hu/mui/Container';
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 HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import {
  useClearNotificationsVacations,
  useGetRequestsReportCollaborator,
  useVacations,
} from 'src/hooks/queryHooks/vacations';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { RequestsTable } from 'src/pages/dashboard/timeOff/components/requestReport';
import { EventName } from 'src/types/amplitude';
import { Role, VacationRequestSources } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { vacationsRoutes } from '../../../routes';
import { useCreateRequestDrawer } from '../../Drawers/CreateRequestDrawer';
import { getRequestDetailsDrawer } from '../../Drawers/RequestDetailsDrawer';
import { EmptyState } from '../../EmptyState/EmptyState';
import { TimeOffHelmet } from '../../helmet/TimeOffHelmet';
import PolicyBalanceDetailDeepLink from '../../policyTypes/PolicyBalanceDetailDeepLink';
import PolicyTypesDetail from '../../policyTypes/PolicyTypesDetail';

import CarouselPolicies from './CarouselPolicies.tsx/CarouselPolicies';

const RequestView = () => {
  const HuGoThemeProvider = useHuGoTheme();
  const { collaborator: collaboratorData, isLoadingViews } = useVacations();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { policyTypes } = collaboratorData;
  const role = searchParams.get('role');
  const vacationId = searchParams.get('vacationId') || '';
  const policyTypeIdParam = searchParams.get('policyTypeId');

  const policyTypeFromNotification = useMemo(() => {
    if (!policyTypeIdParam || !policyTypes?.length) {
      return undefined;
    }
    const parsedId = Number(policyTypeIdParam);

    return policyTypes.find(p => p.id === parsedId);
  }, [policyTypeIdParam, policyTypes]);

  const [openPolicyTypesDetail, setOpenPolicyTypesDetail] = useState(false);
  const { t } = useLokaliseTranslation('time_off');
  useClearNotificationsVacations(Role.COLLABORATOR);

  const form = useForm<{ policyTypeId: number }>({
    defaultValues: {
      policyTypeId: undefined,
    },
  });

  const { watch } = form;

  const policyTypeId = watch('policyTypeId');

  const {
    data,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    countRequest,
  } = useGetRequestsReportCollaborator(policyTypeId);

  const { drawer: requestCreateDrawer, showDrawer: showRequestCreateDrawer } =
    useDrawerV2(args =>
      useCreateRequestDrawer({
        ...args,
        policyTypes,
        user: user!,
        showingAllPolicies: true,
      }),
    );

  const openModalPolicyTypesDetail = (
    e: React.MouseEvent<HTMLButtonElement>,
  ) => {
    e.stopPropagation();
    setOpenPolicyTypesDetail(true);
  };

  const openRequestCreateDrawer = () => {
    showRequestCreateDrawer({});

    logEvent(EventName.TIME_OFF_REQUEST_STARTED, {
      source: VacationRequestSources.MY_TIME_OFF,
    });
  };

  const closeModalPolicyTypesDetail = () => setOpenPolicyTypesDetail(false);

  const hasPolicyType = !!policyTypes?.length;
  const hasMoreThanOnePolicyType = policyTypes?.length > 1;

  const { drawer: requestDetailDrawer, showDrawer: showRequestDetailDrawer } =
    useDrawerV2(args =>
      getRequestDetailsDrawer({
        ...args,
        requestId: Number(vacationId),
      }),
    );

  useEffect(() => {
    if (role === Role.MANAGER) {
      navigate(vacationsRoutes.managerRequestDetail(vacationId));
    }
  }, [role]);

  useEffect(() => {
    if (vacationId) {
      showRequestDetailDrawer({});
    }
  }, [vacationId]);

  return (
    <HuGoThemeProvider>
      <TimeOffHelmet />
      {requestDetailDrawer}
      {policyTypeFromNotification && (
        <PolicyBalanceDetailDeepLink
          key={policyTypeFromNotification.id}
          policyType={policyTypeFromNotification}
        />
      )}
      <Container
        maxWidth="xl"
        sx={{ py: 3, px: 2 }}
      >
        {requestCreateDrawer}
        {!isLoadingViews && (
          <Stack gap={3}>
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
            >
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}
              >
                <Typography
                  variant="globalL"
                  sx={{ fontWeight: 'fontWeightSemiBold' }}
                >
                  {t('request_type_other')}
                </Typography>
              </Stack>
              <Stack sx={{ flexDirection: 'row', gap: 1 }}>
                {hasMoreThanOnePolicyType && (
                  <Button
                    onClick={openModalPolicyTypesDetail}
                    variant="tertiary"
                  >
                    {t('show_more')}
                  </Button>
                )}
                {hasPolicyType && (
                  <Button
                    onClick={openRequestCreateDrawer}
                    variant="primary"
                  >
                    {t('request')}
                  </Button>
                )}
              </Stack>
            </Stack>
            {!hasPolicyType && (
              <EmptyState
                titleProps={{
                  title: t('no_assigned_policy'),
                  description: t('contact_admin_to_resolve_situation'),
                }}
                Icon={IconZoomExclamation}
              />
            )}
            {hasPolicyType && <CarouselPolicies policyTypes={policyTypes} />}

            <RequestsTable
              vacationData={data}
              countRequest={countRequest}
              isLoading={isLoading}
              fetchNextPage={fetchNextPage}
              hasNextPage={hasNextPage}
              isFetchingNextPage={isFetchingNextPage}
            />
            <PolicyTypesDetail
              open={openPolicyTypesDetail}
              onClose={closeModalPolicyTypesDetail}
              policyTypes={policyTypes}
            />
          </Stack>
        )}
        {isLoadingViews && <HuCircularProgress centered />}
      </Container>
    </HuGoThemeProvider>
  );
};

export default RequestView;
