import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

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

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import { type AvatarProps as HuAvatarProps } from '@material-hu/components/design-system/Avatar/types';
import HuChips from '@material-hu/components/design-system/Chip';
import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';
import HuTitle from '@material-hu/components/design-system/Title';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { performanceRoutes } from '../../routes';
import UserListSection from '../UserList/UserListSection';

import CalibrationListRow from './CalibrationListRow';
import CalibrationListSkeleton from './CalibrationListSkeleton';
import { CALIBRATION_FILTERS, CalibrationFilter } from './constants';
import useCalibrations from './hooks/useCalibrations';

const CalibrationList = () => {
  const { id: cycleId } = useParams();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation(['performance']);

  const [filter, setFilter] = useState<CalibrationFilter>(
    CalibrationFilter.ALL,
  );

  const { items, totalCount, isLoading, hasNextPage, fetchNextPage } =
    useCalibrations({ cycleId: cycleId ?? '', filter });

  const handleRowClick = (formReviewId: number) => {
    if (!cycleId) return;
    navigate(performanceRoutes.calibration(cycleId, formReviewId));
  };

  const handleScrollToTop = () => {
    const div = document.getElementById('review-layout');
    if (!div) return;
    div.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const showEmpty = !isLoading && items.length === 0;
  const showList = !isLoading && items.length > 0;
  const showLoadMore = hasNextPage && items.length < totalCount;

  return (
    <Stack sx={{ gap: 3, width: '100%' }}>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 2,
          flexWrap: 'wrap',
        }}
      >
        <HuTitle
          variant="L"
          title={t('cycles.steps.calibration')}
        />
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 2,
            flexWrap: 'wrap',
          }}
        >
          <Typography
            variant="body2"
            sx={{ color: 'text.secondary' }}
          >
            {t('general:filter_by')}
          </Typography>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
              flexWrap: 'wrap',
            }}
          >
            {CALIBRATION_FILTERS.map(item => (
              <HuChips
                key={item.value}
                label={t(item.translationKey)}
                isSelected={filter === item.value}
                onClick={() => setFilter(item.value)}
              />
            ))}
          </Stack>
        </Stack>
      </Stack>

      {isLoading && <CalibrationListSkeleton />}

      {showEmpty && (
        <HuStateCard
          sx={{ p: 3 }}
          slotProps={{
            title: { title: t('general:no_results') },
            avatar: {
              Icon: IconInfoCircle as HuAvatarProps['Icon'],
              size: 'large',
              color: 'primary',
            },
          }}
        />
      )}

      {showList && (
        <UserListSection>
          {items.map(item => (
            <CalibrationListRow
              key={item.formReviewId}
              item={item}
              onClick={handleRowClick}
            />
          ))}
        </UserListSection>
      )}

      {showLoadMore && (
        <TableLoader
          loadedCount={items.length}
          totalCount={totalCount}
          onLoadMore={() => fetchNextPage()}
          onScrollToTop={handleScrollToTop}
        />
      )}
    </Stack>
  );
};

export default CalibrationList;
