import Stack from '@material-hu/mui/Stack';

import { useGetAvailablePoints } from '../../hooks/useGetAvailablePoints';
import { useGetExchanges } from '../../hooks/useGetExchanges';
import { ProductListSkeleton } from '../components/ProductListSkeleton';
import { ExchangesTab } from '../constants';
import { useExchangesTab } from '../hooks/useExchangesTab';

import { HistoryListItem } from './components/HistoryListItem';
import { HistoryStateCard } from './components/HistoryStateCard';

export const History = () => {
  const { exchanges, isLoading, isError, isEmpty, state, refetch } =
    useGetExchanges();
  const { availablePoints } = useGetAvailablePoints();
  const [, setTab] = useExchangesTab();

  const handleRetry = () => refetch();
  const handleShowCatalog = () => setTab(ExchangesTab.Catalog);

  const showList = !isLoading && !isError && !isEmpty;

  return (
    <Stack sx={{ gap: 2 }}>
      {isLoading && <ProductListSkeleton />}
      {showList && (
        <Stack sx={{ gap: 2 }}>
          {exchanges.map(exchange => (
            <HistoryListItem
              key={exchange.id}
              exchange={exchange}
            />
          ))}
        </Stack>
      )}
      <HistoryStateCard
        state={state}
        hasPoints={availablePoints > 0}
        onRetry={handleRetry}
        onShowCatalog={handleShowCatalog}
      />
    </Stack>
  );
};
