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

import { useQueryState } from 'nuqs';
import { IconReload } from '@material-hu/icons/tabler';
import Grid from '@material-hu/mui/Grid';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';

import HuDropdown from '@material-hu/components/design-system/Dropdown';
import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuTabs from '@material-hu/components/design-system/Tabs';
import HuTitle from '@material-hu/components/design-system/Title';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { logEvent } from 'src/config/logging';
import { queryClient } from 'src/config/react-query';
import { ServiceManagementRole } from 'src/pages/dashboard/serviceManagement/types';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ContainerLayout from '../general/ContainerLayout';
import { serviceManagementKeys } from '../queries';

import CoordinatorTasks from './components/CoordinatorTasks';
import HelpDeskGeneralView from './components/HelpDeskGeneralView';
import { useCoordinatorFilters } from './hooks/useCoordinatorFilters';
import { useHelpDeskSelector } from './hooks/useHelpDeskSelector';

const CoordinatorPanel = () => {
  const { t } = useLokaliseTranslation('service_management');

  const {
    selectedHelpDesk,
    helpDeskOptions,
    helpDeskMenuOpen,
    setHelpDeskMenuOpen,
    showHelpDeskSelector,
    handleHelpDeskChange,
  } = useHelpDeskSelector();

  const {
    dashboardFiltersForm,
    taskFiltersForm,
    appliedDashboardFilters,
    appliedTaskFilters,
    handleApplyDashboardFilters,
    handleApplyTaskFilters,
    handleCloseTaskFilters,
    handleCloseDashboardFilters,
    handleResetTaskFilters,
    handleResetDashboardFilters,
    clearAllAppliedFilters,
  } = useCoordinatorFilters();

  // Reset filters whenever the user picks a different help desk, since
  // selected service items, agents and groups belong to the previous one.
  const handleHelpDeskChangeWithReset: typeof handleHelpDeskChange =
    newValue => {
      if (newValue?.value !== selectedHelpDesk?.value) {
        clearAllAppliedFilters();
      }
      handleHelpDeskChange(newValue);
    };

  const [selectedTab, setSelectedTab] = useQueryState('tab', {
    defaultValue: 'dashboard',
  });

  const tabOptions = [
    { label: t('general_view'), value: 'dashboard' },
    { label: t('requests'), value: 'tasks' },
  ];

  const handleTabChange = (_: string, index: number) => {
    setSelectedTab(tabOptions[index].value);
  };

  const handleRefreshDashboard = () => {
    queryClient.invalidateQueries(serviceManagementKeys.helpDesk.all());
    queryClient.invalidateQueries(serviceManagementKeys.tasks.all());
  };

  useEffect(() => {
    logEvent(EventName.SERVICE_MGMT_COORDINATOR_PANEL_VIEWED, {
      role: ServiceManagementRole.COORDINATOR,
    });
  }, []);

  return (
    <Grid
      item
      xs={12}
      sx={{
        position: 'sticky',
        top: 0,
        overflow: 'auto',
        height: 1,
        flexGrow: 1,
        backgroundColor: ({ palette }) => palette.new.background.layout.default,
        maxWidth: { xs: 'calc(100vw - 72px)' },
      }}
    >
      <ContainerLayout
        maxWidth="xl"
        sx={{ py: 4, px: 3, display: 'flex', flexDirection: 'column', gap: 3 }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            width: 1,
            alignItems: 'center',
          }}
        >
          <HuTitle
            title={selectedHelpDesk?.label}
            copetin={t('help_desk')}
            variant="L"
          />
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
            {showHelpDeskSelector && (
              <HuDropdown
                position="right"
                label={selectedHelpDesk?.label ?? ''}
                onClose={() => setHelpDeskMenuOpen(false)}
                onClick={() => setHelpDeskMenuOpen(true)}
                open={helpDeskMenuOpen}
              >
                <HuList>
                  {helpDeskOptions.map(helpDesk => (
                    <HuListItem
                      key={helpDesk.value}
                      text={{ title: helpDesk.label }}
                      onClick={() => handleHelpDeskChangeWithReset(helpDesk)}
                    />
                  ))}
                </HuList>
              </HuDropdown>
            )}
            <HuTooltip description={t('refresh_page')}>
              <IconButton
                onClick={handleRefreshDashboard}
                variant="secondary"
                sx={{ height: 36 }}
              >
                <IconReload size={18} />
              </IconButton>
            </HuTooltip>
          </Stack>
        </Stack>
        <HuTabs
          tabs={tabOptions}
          value={selectedTab}
          onTabChange={handleTabChange}
        />
        {selectedTab === 'dashboard' && (
          <FormProvider {...dashboardFiltersForm}>
            <HelpDeskGeneralView
              helpDeskId={selectedHelpDesk?.value as string}
              helpDeskName={selectedHelpDesk?.label}
              filters={appliedDashboardFilters}
              onApplyFilters={handleApplyDashboardFilters}
              onResetFilters={handleResetDashboardFilters}
              onCloseFilters={handleCloseDashboardFilters}
            />
          </FormProvider>
        )}
        {selectedTab === 'tasks' && (
          <FormProvider {...taskFiltersForm}>
            <CoordinatorTasks
              helpDeskId={selectedHelpDesk?.value as string}
              filters={appliedTaskFilters}
              onApplyFilters={handleApplyTaskFilters}
              onResetFilters={handleResetTaskFilters}
              onCloseFilters={handleCloseTaskFilters}
            />
          </FormProvider>
        )}
      </ContainerLayout>
    </Grid>
  );
};

export default CoordinatorPanel;
