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 { BackstoryElementProps } from 'components/BackstoryTab';
import { CandidateInfo } from 'components/ui/CandidateInfo';
import { Candidate } from "types/types";
import { useAuth } from 'hooks/AuthContext';
import { useAppState, useSelectedCandidate } from 'hooks/GlobalContext';

interface CandidatePickerProps extends BackstoryElementProps {
    onSelect?: (candidate: Candidate) => void
};

const CandidatePicker = (props: CandidatePickerProps) => {
    const { onSelect } = props;
    const { apiClient, user } = useAuth();
    const { selectedCandidate, setSelectedCandidate } = useSelectedCandidate();
    const navigate = useNavigate();
    const { setSnack } = useAppState();
    const [candidates, setCandidates] = useState<Candidate[] | null>(null);

    useEffect(() => {
        if (candidates !== null) {
            return;
        }
        const getCandidates = async () => {
            try {
                const results = await apiClient.getCandidates();
                const candidates: Candidate[] = results.data;
                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;
                });
                setCandidates(candidates);
            } catch (err) {
                setSnack("" + err);
            }
        };

        getCandidates();
    }, [candidates, setSnack]);

    return (
        <Box sx={{display: "flex", flexDirection: "column"}}>
            {user?.isAdmin && 
                <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", justifyContent: "center" }}>
                {candidates?.map((u, i) => 
                <Box key={`${u.username}`} 
                        onClick={() => { onSelect ? onSelect(u) : setSelectedCandidate(u); }}
                        sx={{ cursor: "pointer" }}>
                        {selectedCandidate?.id === u.id &&
                            <CandidateInfo sx={{ maxWidth: "320px", "cursor": "pointer", backgroundColor: "#f0f0f0", "&:hover": { border: "2px solid orange" } }} candidate={u} />
                        }
                        {selectedCandidate?.id !== u.id &&
                            <CandidateInfo sx={{ maxWidth: "320px", "cursor": "pointer", border: "2px solid transparent", "&:hover": { border: "2px solid orange" } }} candidate={u} />
                        }
                </Box>
                )}
            </Box>
        </Box>
    );
};

export {
  CandidatePicker
};