import { FormProvider } from 'react-hook-form';

import { IconInfoCircle } from '@material-hu/icons/tabler';
import { type Theme, Typography } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack';

import HuSelectionCard from '@material-hu/components/composed-components/SelectionCard/';
import Alert from '@material-hu/components/design-system/Alert';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuDrawer from '@material-hu/components/design-system/Drawer';
import HuFormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import RadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';
import HuFormSwitcher from '@material-hu/components/design-system/Switcher/form';
import HuTitle from '@material-hu/components/design-system/Title';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import {
  type CoordinatorTaskFilters,
  type FilterFormValues,
  type ServiceManagementRole,
  TaskReportType,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { coordinatorTaskFilters, tasksReportFormFields } from '../form/form';
import { useReportDownload } from '../hooks/useReportDownload';
import { type FilterType } from '../types';

import CollaboratorPanelFilterDrawer from './CollaboratorPanelFilterDrawer';
import FiltersDrawer from './FiltersDrawer';

const cardContainerSx = {
  width: 1,
  backgroundColor: ({ palette }: Theme) => palette.new.background.elements.grey,
  border: 'unset',
};

type Props = {
  open: boolean;
  onClose: () => void;
  appliedFilters: CoordinatorTaskFilters | FilterFormValues | null;
  appliedFiltersCount: number;
  helpDeskId?: string | null;
  filterType?: FilterType;
  role: ServiceManagementRole;
};

const DownloadTasksReportDrawer = ({
  open,
  onClose,
  appliedFilters,
  appliedFiltersCount,
  helpDeskId,
  filterType = 'agent',
  role,
}: Props) => {
  const { t } = useLokaliseTranslation(['service_management', 'users']);

  const {
    form,
    agentFiltersForm,
    coordinatorFiltersForm,
    filtersDrawerOpen,
    selectedReportType,
    includeSegmentationsValue,
    includeProfileFieldsValue,
    selectedSegmentations,
    selectedProfileFields,
    loadingSegmentations,
    dataSegmentations,
    isLoadingProfileFields,
    profileFieldsOptions,
    segmentationOptions,
    getAlertTitleProps,
    handleCloseFiltersDrawer,
    handleResetLocalFiltersForm,
    handleApplyLocalFilters,
    handleDownload,
    handleResetFilters,
    missingSelections,
    isLoadingDownload,
  } = useReportDownload({
    open,
    onClose,
    appliedFilters,
    appliedFiltersCount,
    helpDeskId,
    filterType,
    role,
  });

  const renderFiltersDrawer = () => {
    if (filterType === 'coordinator') {
      return (
        <FormProvider {...coordinatorFiltersForm}>
          <CollaboratorPanelFilterDrawer
            open={filtersDrawerOpen}
            onClose={handleCloseFiltersDrawer}
            onReset={handleResetLocalFiltersForm}
            onApply={handleApplyLocalFilters}
            helpDeskId={helpDeskId ?? undefined}
            filterConfig={coordinatorTaskFilters}
            showStatuses
            showRequesters
            showCollaboratorTypes
            showBack
          />
        </FormProvider>
      );
    }

    return (
      <FormProvider {...agentFiltersForm}>
        <FiltersDrawer
          open={filtersDrawerOpen}
          onClose={handleCloseFiltersDrawer}
          onReset={handleResetLocalFiltersForm}
          onApply={handleApplyLocalFilters}
          showBackButton
        />
      </FormProvider>
    );
  };

  return (
    <>
      {renderFiltersDrawer()}
      <HuDrawer
        open={open}
        onClose={() => {
          form.reset();
          onClose();
        }}
        title={t('download_report')}
        primaryButtonProps={{
          fullWidth: true,
          children: t('download'),
          onClick: handleDownload,
          disabled: !form.formState.isValid || missingSelections,
          loading: isLoadingDownload,
        }}
        secondaryButtonProps={{
          fullWidth: true,
          children: t('reset'),
          onClick: handleResetFilters,
          disabled: isLoadingDownload,
        }}
        footer={<Alert {...getAlertTitleProps()} />}
      >
        <FormProvider {...form}>
          <Stack sx={{ gap: 2 }}>
            <HuCardContainer sx={cardContainerSx}>
              <FormInputClassic
                name={tasksReportFormFields.email()}
                inputProps={{
                  label: t('report_form_email_label'),
                  placeholder: t('report_form_email_placeholder'),
                  hasCounter: false,
                }}
              />
            </HuCardContainer>
            <HuTitle
              variant="S"
              title={t('report_form_personalization_title')}
              description={t('report_form_personalization_description')}
            />
            <HuCardContainer sx={cardContainerSx}>
              <Stack sx={{ gap: 2 }}>
                <Typography
                  variant="globalS"
                  fontWeight="fontWeightSemiBold"
                >
                  {t('report_type')}
                </Typography>
                <Stack sx={{ gap: 1 }}>
                  <HuSelectionCard
                    checked={selectedReportType === TaskReportType.CONSOLIDATED}
                    onClick={() => {
                      form.setValue(
                        tasksReportFormFields.reportType(),
                        TaskReportType.CONSOLIDATED,
                      );
                    }}
                    fullWidth
                  >
                    <RadioButton
                      label={t('consolidated_report')}
                      description={t('consolidated_report_description')}
                      isActive={
                        selectedReportType === TaskReportType.CONSOLIDATED
                      }
                    />
                  </HuSelectionCard>
                </Stack>
                <HuSelectionCard
                  checked={selectedReportType === TaskReportType.SERVICE}
                  onClick={() => {
                    form.setValue(
                      tasksReportFormFields.reportType(),
                      TaskReportType.SERVICE,
                    );
                  }}
                  fullWidth
                >
                  <RadioButton
                    label={t('services_report')}
                    description={t('services_report_description')}
                    isActive={selectedReportType === TaskReportType.SERVICE}
                  />
                </HuSelectionCard>
              </Stack>
            </HuCardContainer>
            <HuCardContainer sx={cardContainerSx}>
              <Stack sx={{ gap: 1.5 }}>
                <HuFormSwitcher
                  name={tasksReportFormFields.includeSegmentations()}
                  switcherProps={{
                    title: t('report_form_include_segmentations'),
                    Icon: (
                      <HuTooltip
                        title={t(
                          'report_form_include_segmentations_helper_text',
                        )}
                      >
                        <IconInfoCircle size={20} />
                      </HuTooltip>
                    ),
                  }}
                />
                {includeSegmentationsValue && (
                  <>
                    {loadingSegmentations && <HuCircularProgress />}
                    {!loadingSegmentations && dataSegmentations && (
                      <HuFormAutocomplete
                        name={tasksReportFormFields.segmentations()}
                        options={segmentationOptions || []}
                        autocompleteProps={{
                          isServerFiltered: false,
                          ...(selectedSegmentations?.length === 0 && {
                            placeholder: t('select_segmentations'),
                          }),
                          multiple: true,
                          disableCloseOnSelect: true,
                        }}
                      />
                    )}
                  </>
                )}
              </Stack>
            </HuCardContainer>
            <HuCardContainer sx={cardContainerSx}>
              <Stack sx={{ gap: 1.5 }}>
                <HuFormSwitcher
                  name={tasksReportFormFields.includeProfileFields()}
                  switcherProps={{
                    title: t('report_form_include_profile_fields'),
                    Icon: (
                      <HuTooltip
                        title={t(
                          'report_form_include_profile_fields_helper_text',
                        )}
                      >
                        <IconInfoCircle size={20} />
                      </HuTooltip>
                    ),
                  }}
                />
                {includeProfileFieldsValue && (
                  <>
                    {isLoadingProfileFields && <HuCircularProgress />}
                    {!isLoadingProfileFields && profileFieldsOptions && (
                      <HuFormAutocomplete
                        name={tasksReportFormFields.profileFields()}
                        options={profileFieldsOptions}
                        autocompleteProps={{
                          isServerFiltered: false,
                          placeholder:
                            selectedProfileFields?.length === 0
                              ? t('select_profile_fields')
                              : undefined,
                          multiple: true,
                          disableCloseOnSelect: true,
                        }}
                      />
                    )}
                  </>
                )}
              </Stack>
            </HuCardContainer>
          </Stack>
        </FormProvider>
      </HuDrawer>
    </>
  );
};

export default DownloadTasksReportDrawer;
