import { type FC, Fragment } from 'react';

import { IconInfoSquareRounded } from '@material-hu/icons/tabler';
import Container from '@material-hu/mui/Container';
import Divider from '@material-hu/mui/Divider';
import Grid from '@material-hu/mui/Grid';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';
import HuTitle from '@material-hu/components/design-system/Title';

import {
  type ServiceItem,
  ServiceItemDesignLayout,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import InfiniteList from 'src/components/list/InfiniteList';

import CatalogItemCard from './components/CardItem/ServiceItemCard';
import SkeletonCatalogItemCard from './components/CardItem/SkeletonServiceItemCard';
import Categories from './components/Categories/Categories';
import EmptyCatalogItems from './components/EmptyServiceItems';
import GridLayoutSkeleton from './components/LayoutSkeletons/GridLayoutSkeleton';
import ListLayoutSkeleton from './components/LayoutSkeletons/ListLayoutSkeleton';
import CatalogItemList from './components/ListItem/ServiceItemList';
import SkeletonCatalogItemList from './components/ListItem/SkeletonServiceItemList';
import ToggleDisplayLayout from './components/ToggleDisplayLayout';
import { useServiceItems } from './hooks/useServiceItems';

const TOP_BAR_HEIGHT = '73px';

export const Requests: FC = () => {
  const { t } = useLokaliseTranslation('service_management');
  const theme = useTheme();

  const {
    HugoThemeProvider,
    designType,
    query,
    setQuery,
    categoriesData,
    isLoadingCategories,
    isLoadingModuleConfig,
    data,
    isLoadingCatalogItems,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    currentCategory,
    showNoServiceItems,
    showAll,
    handleUpdateCurrentCategory,
    handleChangeDesignType,
    handleStartServiceItem,
    handleNavigateToServicePortal,
  } = useServiceItems();

  return (
    <HugoThemeProvider>
      <TaskFocusHeader
        title={t('service_catalog')}
        onBack={handleNavigateToServicePortal}
      />
      <Divider />
      <Grid
        container
        sx={{
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
          height: `calc(100% - ${TOP_BAR_HEIGHT})`,
          overflow: 'hidden',
        }}
      >
        {!showNoServiceItems && (
          <Grid
            item
            xs={3}
            md={2}
            id="category-sidebar"
            sx={{ height: 1, overflow: 'auto' }}
          >
            <Categories
              categoriesData={categoriesData}
              loading={isLoadingCategories || isLoadingModuleConfig}
              onClickCategory={handleUpdateCurrentCategory}
              currentCategory={currentCategory}
              allSelected={showAll}
            />
          </Grid>
        )}
        <Grid
          item
          xs={showNoServiceItems ? 12 : 9}
          md={showNoServiceItems ? 12 : 10}
          sx={{ height: '100%', overflow: 'auto' }}
        >
          <Container
            maxWidth="lg"
            sx={{ pt: 4, px: 2 }}
          >
            {isLoadingCatalogItems &&
              designType === ServiceItemDesignLayout.GRID && (
                <GridLayoutSkeleton />
              )}
            {isLoadingCatalogItems &&
              designType === ServiceItemDesignLayout.LIST && (
                <ListLayoutSkeleton />
              )}
            {!isLoadingCatalogItems && showNoServiceItems && (
              <EmptyCatalogItems />
            )}
            {!isLoadingCatalogItems && !showNoServiceItems && (
              <>
                <Stack sx={{ gap: 3 }}>
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      gap: 2,
                    }}
                  >
                    <HuTitle
                      variant="L"
                      title={t('service_items')}
                      description={t('new_request_description')}
                      sx={{ flex: 1 }}
                    />
                    <ToggleDisplayLayout
                      designType={designType}
                      onChangeDesignType={handleChangeDesignType}
                    />
                  </Stack>
                  <HuSearch
                    value={query}
                    placeholder={t('search_request')}
                    onChange={value => setQuery(value)}
                  />
                </Stack>
                <Stack sx={{ gap: 3, pb: 6, mt: 3 }}>
                  <Typography
                    variant="globalS"
                    sx={{ color: theme.palette.new.text.neutral.lighter }}
                  >
                    {showAll ? t('all') : currentCategory?.name}
                  </Typography>
                  <InfiniteList
                    isSuccess={!!data}
                    isLoading={isLoadingCatalogItems}
                    isEmpty={!data?.pages[0]?.data?.items?.length}
                    noResultsLabel={
                      <HuStateCard
                        sx={{ p: 3 }}
                        slotProps={{
                          title: {
                            title: t('no_results_found'),
                            description: t('try_again_search'),
                          },
                          avatar: {
                            color: 'primary',
                            Icon: IconInfoSquareRounded,
                          },
                        }}
                      />
                    }
                    fetchNextPage={fetchNextPage}
                    hasNextPage={hasNextPage}
                    isFetchingNextPage={isFetchingNextPage}
                    renderSkeleton={
                      <>
                        {designType === ServiceItemDesignLayout.LIST && (
                          <SkeletonCatalogItemList />
                        )}
                        {designType === ServiceItemDesignLayout.GRID && (
                          <SkeletonCatalogItemCard />
                        )}
                      </>
                    }
                  >
                    {designType === ServiceItemDesignLayout.LIST && (
                      <Stack sx={{ gap: 1 }}>
                        {data?.pages?.map((group, i) => (
                          <Stack
                            key={i}
                            sx={{ gap: 1.5 }}
                          >
                            {group.data?.items?.map(
                              (catalogItem: ServiceItem) => (
                                <Fragment key={catalogItem.id}>
                                  <CatalogItemList
                                    catalogItem={catalogItem}
                                    onClickAction={() =>
                                      handleStartServiceItem(catalogItem)
                                    }
                                  />
                                </Fragment>
                              ),
                            )}
                          </Stack>
                        ))}
                      </Stack>
                    )}
                    {designType === ServiceItemDesignLayout.GRID && (
                      <Grid
                        container
                        spacing={3}
                      >
                        {data?.pages?.map((group, i) => (
                          <Fragment key={i}>
                            {group.data?.items?.map(
                              (catalogItem: ServiceItem) => (
                                <Fragment key={catalogItem.id}>
                                  <CatalogItemCard
                                    catalogItem={catalogItem}
                                    onClickAction={() =>
                                      handleStartServiceItem(catalogItem)
                                    }
                                  />
                                </Fragment>
                              ),
                            )}
                          </Fragment>
                        ))}
                      </Grid>
                    )}
                  </InfiniteList>
                </Stack>
              </>
            )}
          </Container>
        </Grid>
      </Grid>
    </HugoThemeProvider>
  );
};

export default Requests;
