import { useNavigate } from 'react-router-dom';

import { IconAlertCircle, IconSchool } from '@material-hu/icons/tabler';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import { type PaginatedQueryState } from 'src/hooks/usePaginatedQueryState';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { pathsRoutes } from '../../../routes';

import TableSkeleton from './TableSkeleton';

type TableStateProps = {
  queryState: PaginatedQueryState;
  refetchPaths: () => void;
};

const TableState = ({ queryState, refetchPaths }: TableStateProps) => {
  const { t } = useLokaliseTranslation('learning');
  const navigate = useNavigate();

  if (queryState.isLoading) return <TableSkeleton />;

  const avatarIcon = queryState.isError ? IconSchool : IconAlertCircle;

  const handleButtonAction = () => {
    if (queryState.isError) refetchPaths();
    else navigate(pathsRoutes.new());
  };

  const tableStatesTranslations = () => {
    if (queryState.isEmpty) {
      return {
        title: t('empty.paths.created.title'),
        description: t('empty.paths.created.description'),
        buttonText: t('path.create'),
      };
    }

    if (queryState.isEmptySearch) {
      return {
        title: t('empty.paths.search.title'),
        description: t('empty.paths.search.description'),
        buttonText: t('path.create'),
      };
    }

    return {
      title: t('empty.error.title'),
      description: t('empty.error.description'),
      buttonText: t('empty.error.action'),
    };
  };

  const { title, description, buttonText } = tableStatesTranslations();

  return (
    <HuTableRow>
      <HuTableCell colSpan={12}>
        <HuStateCard
          cardContained={false}
          slotProps={{
            avatar: {
              Icon: avatarIcon,
            },
            title: {
              title,
              description,
            },
            button: {
              children: buttonText,
              onClick: handleButtonAction,
            },
          }}
        />
      </HuTableCell>
    </HuTableRow>
  );
};

export default TableState;
