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 { JobInfo } from 'components/ui/JobInfo';
import { Job, JobFull } from "types/types";
import { useAuth } from 'hooks/AuthContext';
import { useAppState, useSelectedJob } from 'hooks/GlobalContext';

interface JobPickerProps extends BackstoryElementProps {
    onSelect?: (job: JobFull) => void
};

const JobPicker = (props: JobPickerProps) => {
    const { onSelect } = props;
    const { apiClient } = useAuth();
    const { selectedJob, setSelectedJob } = useSelectedJob();
    const { setSnack } = useAppState();
    const [jobs, setJobs] = useState<JobFull[] | null>(null);

    useEffect(() => {
        if (jobs !== null) {
            return;
        }
        const getJobs = async () => {
            try {
                const results = await apiClient.getJobs();
                const jobs: JobFull[] = results.data;
                jobs.sort((a, b) => {
                    let result = a.company?.localeCompare(b.company || '');
                    if (result === 0) {
                        result = a.title?.localeCompare(b.title || '');
                    }
                    return result || 0;
                });
                setJobs(jobs);
            } catch (err) {
                setSnack("" + err);
            }
        };

        getJobs();
    }, [jobs, setSnack]);

    return (
        <Box sx={{display: "flex", flexDirection: "column", mb: 1}}>
            <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", justifyContent: "center" }}>
                {jobs?.map((j, i) => 
                <Box key={`${j.id}`} 
                    onClick={() => { onSelect ? onSelect(j) : setSelectedJob(j); }}
                    sx={{ cursor: "pointer" }}>
                    {selectedJob?.id === j.id &&
                        <JobInfo sx={{ maxWidth: "320px", "cursor": "pointer", backgroundColor: "#f0f0f0", "&:hover": { border: "2px solid orange" } }} job={j} />
                    }
                    {selectedJob?.id !== j.id &&
                        <JobInfo sx={{ maxWidth: "320px", "cursor": "pointer", border: "2px solid transparent", "&:hover": { border: "2px solid orange" } }} job={j} />
                    }
                </Box>
                )}
            </Box>
        </Box>
    );
};

export {
  JobPicker
};