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

import { IconDownload, IconFilter } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import { IconButton } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack';

import BadgeCountButton from '@material-hu/components/composed-components/BadgeCountButton';
import HuTitle from '@material-hu/components/design-system/Title';
import Tooltip from '@material-hu/components/design-system/Tooltip';

import { ServiceManagementRole } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import DownloadTasksReportDrawer from './components/DownloadTasksReportDrawer';
import FiltersDrawer from './components/FiltersDrawer';
import NewViewFiltersAlert from './components/NewViewFiltersAlert';
import TasksTable from './components/TasksTable';
import ViewSidebar from './components/ViewSidebar';
import ViewTitleSkeleton from './components/ViewTitleSkeleton';
import { useTicketViews } from './hooks/useTicketViews';

const SIDEBAR_EXPANDED_WIDTH = 280;
const SIDEBAR_COLLAPSED_WIDTH = 72;

const Tickets: FC = () => {
  const { t } = useLokaliseTranslation('service_management');

  const {
    HugoThemeProvider,
    isSidebarCollapsed,
    setIsSidebarCollapsed,
    filterDrawerOpen,
    setFilterDrawerOpen,
    appliedFilters,
    appliedFiltersCount,
    stableSelectedViewHasNewFilters,
    downloadReportDrawerOpen,
    setDownloadReportDrawerOpen,
    alertRef,
    form,
    paginationForm,
    Search,
    Pagination,
    HuTableSortingHeader,
    currentView,
    isLoadingCurrentView,
    viewId,
    tasks,
    isLoadingTasks,
    isPreviousData,
    isError,
    refetch,
    selectedTasks,
    query,
    isLoadingModuleConfiguration,
    hasSlasConfigured,
    hasFilters,
    allChecked,
    assignButtonDisabled,
    resetFiltersDisabled,
    canDownloadTaskReport,
    SingleAssignmentPopoverComponent,
    MultipleAssignmentPopoverComponent,
    multipleAssignmentConfirmationModal,
    singleAssignmentConfirmationModal,
    confirmSaveViewModal,
    handleRowClick,
    handleCheckboxClick,
    handleSelectAll,
    handleOpenSingleReassign,
    handleCloseFilterDrawer,
    handleResetFilters,
    handleApplyFilters,
    handleDismissNewFilters,
    handleSaveAsNewView,
    handleSaveViewChanges,
    handleSelectBaseView,
    handleSelectView,
    handleOpenMultipleAssignmentMenu,
  } = useTicketViews();

  return (
    <HugoThemeProvider>
      {multipleAssignmentConfirmationModal}
      {singleAssignmentConfirmationModal}
      {confirmSaveViewModal}
      <Stack
        sx={{
          position: 'sticky',
          overflowY: 'auto',
          overflowX: 'hidden',
          top: 0,
          height: 1,
          width: isSidebarCollapsed
            ? SIDEBAR_COLLAPSED_WIDTH
            : SIDEBAR_EXPANDED_WIDTH,
          minWidth: isSidebarCollapsed
            ? SIDEBAR_COLLAPSED_WIDTH
            : SIDEBAR_EXPANDED_WIDTH,
          transition: 'width 0.2s ease-in-out, min-width 0.2s ease-in-out',
        }}
      >
        <ViewSidebar
          viewId={viewId}
          onSelectView={handleSelectView}
          onSelectBaseView={handleSelectBaseView}
          isCollapsed={isSidebarCollapsed}
          onToggleCollapse={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
        />
      </Stack>
      <Stack
        sx={{
          overflowY: 'auto',
          overflowX: 'hidden',
          maxWidth: '100%',
          mx: 'auto',
          height: 1,
          flex: 1,
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
        }}
      >
        {/* Animation using grid-template-rows instead of Mui Collapse because it breaks the layout and causes overlap */}
        <Box
          sx={{
            display: 'grid',
            gridTemplateRows: stableSelectedViewHasNewFilters ? '1fr' : '0fr',
            transition: 'grid-template-rows 0.3s ease-in-out',
          }}
        >
          <Box sx={{ overflow: 'hidden' }}>
            <NewViewFiltersAlert
              view={currentView}
              ref={alertRef}
              onDismiss={handleDismissNewFilters}
              onSave={currentView ? handleSaveViewChanges : handleSaveAsNewView}
              onSaveToNewView={handleSaveAsNewView}
            />
          </Box>
        </Box>
        <Stack sx={{ px: 3, py: 2 }}>
          <FormProvider {...paginationForm}>
            <Stack sx={{ gap: 3 }}>
              {isLoadingCurrentView && <ViewTitleSkeleton />}
              {!isLoadingCurrentView && (
                <HuTitle
                  variant="L"
                  copetin={t('requests')}
                  title={!viewId ? t('all') : (currentView?.name ?? '')}
                />
              )}
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}
              >
                <Search />
                <BadgeCountButton
                  count={appliedFiltersCount}
                  buttonProps={{
                    variant: 'secondary',
                    startIcon: <IconFilter />,
                    onClick: () => setFilterDrawerOpen(true),
                  }}
                >
                  {appliedFiltersCount > 0
                    ? t('general:filtered')
                    : t('filter')}
                </BadgeCountButton>
                {canDownloadTaskReport && (
                  <>
                    <Tooltip description={t('download_report')}>
                      <IconButton
                        aria-label={t('general:download')}
                        variant="secondary"
                        onClick={() => setDownloadReportDrawerOpen(true)}
                      >
                        <IconDownload />
                      </IconButton>
                    </Tooltip>
                    <DownloadTasksReportDrawer
                      open={downloadReportDrawerOpen}
                      onClose={() => setDownloadReportDrawerOpen(false)}
                      appliedFilters={appliedFilters}
                      appliedFiltersCount={appliedFiltersCount}
                      role={ServiceManagementRole.AGENT}
                    />
                  </>
                )}
                <FormProvider {...form}>
                  <FiltersDrawer
                    open={filterDrawerOpen}
                    onClose={handleCloseFilterDrawer}
                    onReset={handleResetFilters}
                    onApply={handleApplyFilters}
                    resetDisabled={resetFiltersDisabled}
                    showBackButton={downloadReportDrawerOpen}
                  />
                </FormProvider>
              </Stack>
              <Stack sx={{ gap: 2 }}>
                {!isLoadingModuleConfiguration && (
                  <>
                    <TasksTable
                      tasks={tasks}
                      selectedTasks={selectedTasks}
                      isLoadingTasks={isLoadingTasks}
                      isPreviousData={isPreviousData}
                      handleRowClick={handleRowClick}
                      handleCheckboxClick={handleCheckboxClick}
                      handleSelectAll={handleSelectAll}
                      handleOpenSingleReassign={handleOpenSingleReassign}
                      allChecked={allChecked}
                      hasSlasConfigured={hasSlasConfigured}
                      hasFilters={hasFilters}
                      hasSearch={!!query}
                      assignButtonDisabled={assignButtonDisabled}
                      handleOpenMultipleAssignmentMenu={
                        handleOpenMultipleAssignmentMenu
                      }
                      MultipleAssignmentPopoverComponent={
                        MultipleAssignmentPopoverComponent
                      }
                      isError={isError}
                      Pagination={Pagination}
                      SortingHeader={HuTableSortingHeader}
                      onRefetch={refetch}
                      showAgentGroup={false}
                    />
                    {/* Popover is positioned outside the table element to prevent event propagations (not supported in onClose) */}
                    {SingleAssignmentPopoverComponent}
                  </>
                )}
              </Stack>
            </Stack>
          </FormProvider>
        </Stack>
      </Stack>
    </HugoThemeProvider>
  );
};

export default Tickets;
