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

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

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

    useEffect(() => {
        if (jobs !== null) {
            return;
        }
        const getJobs = async () => {
            try {
                const results = await apiClient.getJobs();
                const jobs: Job[] = 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) => 
                    <Paper key={`${j.id}`}
                        onClick={() => { onSelect ? onSelect(j) : setSelectedJob(j); }}
                        sx={{ cursor: "pointer" }}>
                        <JobInfo variant="small"
                            sx={{
                                maxWidth: "100%",
                                minWidth: "320px",
                                width: "320px",
                                "cursor": "pointer",
                                backgroundColor: (selectedJob?.id === j.id) ? "#f0f0f0" : "inherit",
                                border: "2px solid transparent",
                                "&:hover": {
                                    border: "2px solid orange"
                                }
                            }}
                            job={j}
                        />
                    </Paper>
                )}
            </Box>
        </Box>
    );
};

export {
  JobPicker
};