import React, { useContext, useEffect, useState } from 'react';
import { Grid } from '@material-ui/core';
import { ContentWrapper } from 'components/content-wrapper/content-wrapper';
import { Ticket } from 'components/ticket/ticket';
import { useFetch } from 'utils/use-fetch';
import { AppContext } from 'context/app-context';
import { Typography } from '@material-ui/core';
import { TicketType } from 'common/types';
import { CategoriesList } from 'components/ticket/categories-list';
import { v4 as uuidv4 } from 'uuid';

interface allTypes {
  [key: string]: number;
}

export function getTicketTypeCategories(types: TicketType[]) {
  let countedTypes = types.reduce((allTypes: allTypes, type) => {
    if (type.label in allTypes) {
      allTypes[type.label]++;
    } else {
      allTypes[type.label] = 1;
    }
    return allTypes;
  }, {});
  return countedTypes;
}

export const Sell: React.FC = () => {
  const ticketTypes =
    useFetch('http://localhost:8000/tickets/type/list-all').response ?? [];

  const [ticketsToSell, setTIcketToSell] = useState<TicketType[]>(
    JSON.parse(localStorage.getItem('sell') || '{}').ticketTypes || []
  );

  const { state } = useContext(AppContext);

  useEffect(() => {
    localStorage.setItem('sell', JSON.stringify(state.sell));
    setTIcketToSell(state.sell.ticketTypes);
  }, [state.sell]);

  return (
    <>
      <ContentWrapper>
        <Grid item xs={12} style={{ marginLeft: 50 }}>
          <Typography component="h1" variant="h3" style={{ marginBottom: 50 }}>
            Dostupné lístky
          </Typography>
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {ticketTypes.map(({ label, type, tariff, price }, index) => {
              const id = uuidv4();
              return (
                <Ticket
                  key={`${label}-${index}`}
                  id={id}
                  type={type}
                  tariff={tariff}
                  label={label}
                  price={price}
                />
              );
            })}
          </div>
        </Grid>
      </ContentWrapper>
      {!!ticketsToSell.length && <CategoriesList tickets={ticketsToSell} />}
    </>
  );
};
