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, CandidateAI } from "types/types";
import { useAuth } from 'hooks/AuthContext';
import { useAppState, useSelectedCandidate } from 'hooks/GlobalContext';
import { Paper } from '@mui/material';

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

const CandidatePicker = (props: CandidatePickerProps) => {
    const { onSelect, sx } = 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) => {
                    const aIsAi = 'isAI' in a ? 1 : 0;
                    const bIsAi = 'isAI' in b ? 1 : 0;
                    let result = aIsAi - bIsAi;
                    if (result === 0) {
                        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", ...sx }}>
            <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", justifyContent: "center" }}>
                {candidates?.map((u, i) => 
                    <Paper key={`${u.username}`}
                        onClick={() => { onSelect ? onSelect(u) : setSelectedCandidate(u); }}
                        sx={{ cursor: "pointer" }}>
                        <CandidateInfo variant="small" sx={{ maxWidth: "320px", "cursor": "pointer", backgroundColor: (selectedCandidate?.id === u.id) ? "#f0f0f0" : "inherit", border: "2px solid transparent", "&:hover": { border: "2px solid orange" } }} candidate={u} />
                    </Paper>
                )}
            </Box>
        </Box>
    );
};

export {
  CandidatePicker
};