import { Context } from '../data/Context';
import { useContext, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
  convertResultsToSpeedFlowchartResult,
  SpeedFlowchartResult,
} from '../data/SpeedFlowchart';
import { Card, CardContent, Grid, Typography } from '@mui/material';

/**
 *
 * @return {JSX.Element} speed flowchart page
 */
export default function SpeedFlowchartPage() {
  const { competitionId, categoryId } = useParams();
  const { api } = useContext(Context);

  const [flowchartResult, setFlowchartResult] =
    useState<SpeedFlowchartResult>();

  useEffect(() => {
    if (competitionId === undefined || categoryId === undefined) {
      return;
    }

    api.getCompetitionResults(competitionId, categoryId).then(r => {
      const flowchartResult = convertResultsToSpeedFlowchartResult(r);
      console.log(flowchartResult);
      setFlowchartResult(flowchartResult);
    });
  }, []);

  return (
    <>
      <h1>RESULT:</h1>
      <Grid container spacing={2}>
        {flowchartResult?.rounds.map((round, roundKey) => (
          <Grid key={`flowchart-column-${roundKey}`} item xs={12 / 5}>
            <h3>{round.roundName}</h3>
            <Grid container spacing={2}>
              {round.pairs.map((pair, pairKey) => (
                <Grid
                  key={`flowchart-column-${roundKey}-pair-${pairKey}`}
                  item
                  xs={12}
                >
                  <Card>
                    <CardContent>
                      <Typography
                        sx={{
                          fontWeight: pair.winner === 'A' ? 'bold' : 'plain',
                        }}
                      >
                        A: {pair.laneA?.firstName} {pair.laneA?.lastName}
                      </Typography>
                      <Typography
                        sx={{
                          fontWeight: pair.winner === 'B' ? 'bold' : 'plain',
                        }}
                      >
                        B: {pair.laneB?.firstName} {pair.laneB?.lastName}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Grid>
        ))}
      </Grid>
    </>
  );
}
