import React, { useEffect, useState } from 'react';
import { useNavigate } from "react-router-dom";
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';

import { BackstoryPageProps } from '../components/BackstoryTab';
import { CandidateInfo } from 'components/CandidateInfo';
import { connectionBase } from '../utils/Global';
import { Candidate } from "../types/types";

const CandidateListingPage = (props: BackstoryPageProps) => {
    const navigate = useNavigate();
    const { sessionId, setSnack } = props;
    const [candidates, setCandidates] = useState<Candidate[] | undefined>(undefined);

    useEffect(() => {
        if (candidates !== undefined) {
            return;
        }
        const fetchCandidates = async () => {
            try {
                let response;
                response = await fetch(`${connectionBase}/api/u/${sessionId}`, {
                    credentials: 'include',
                });
                if (!response.ok) {
                    throw new Error('Session not found');
                }
                const candidates: Candidate[] = await response.json();
                candidates.sort((a, b) => {
                    let result = a.lastName.localeCompare(b.lastName);
                    if (result === 0) {
                        result = a.firstName.localeCompare(b.firstName);
                    }
                    if (result === 0) {
                        result = a.username.localeCompare(b.username);
                    }
                    return result;
                });
                console.log(candidates);
                setCandidates(candidates);
            } catch (err) {
                setSnack("" + err);
            }
        };

        fetchCandidates();
    }, [candidates, sessionId, setSnack]);

    return (
        <Box sx={{display: "flex", flexDirection: "column"}}>
          <Box sx={{ p: 1, textAlign: "center" }}>
            Not seeing a candidate you like? 
            <Button 
              variant="contained" 
              sx={{m: 1}}
              onClick={() => { navigate('/generate-candidate')}}>
              Generate your own perfect AI candidate!
            </Button>
          </Box>
        <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap"}}>
                {candidates?.map((u, i) => 
                <Box key={`${u.username}`} 
                    onClick={(event: React.MouseEvent<HTMLDivElement>) : void => {
                        navigate(`/u/${u.username}`)
                    }}
                    sx={{ cursor: "pointer" }}
                    >
                    <CandidateInfo sessionId={sessionId} sx={{ maxWidth: "320px", "cursor": "pointer", "&:hover": { border: "2px solid orange" }, border: "2px solid transparent" }} user={u} />
                </Box>
            )}
        </Box>
        </Box>
    );
};

export {
  CandidateListingPage
};