import React, { useEffect, useState } from 'react';
import {
    Box,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Typography,
    FormControl,
    Select,
    MenuItem,
    InputLabel,
    Chip,
    Divider,
    IconButton,
    Tooltip
} from '@mui/material';
import {
    KeyboardArrowUp as ArrowUpIcon,
    KeyboardArrowDown as ArrowDownIcon,
    Business as BusinessIcon,
    Work as WorkIcon,
    Schedule as ScheduleIcon
} from '@mui/icons-material';
import { JobInfo } from 'components/ui/JobInfo';
import { Job } from "types/types";
import { useAuth } from 'hooks/AuthContext';
import { useAppState, useSelectedJob } from 'hooks/GlobalContext';
import { Navigate, useNavigate, useParams } from 'react-router-dom';

type SortField = 'updatedAt' | 'createdAt' | 'company' | 'title';
type SortOrder = 'asc' | 'desc';

interface JobViewerProps {
    onSelect?: (job: Job) => void;
}

const JobViewer: React.FC<JobViewerProps> = ({ onSelect }) => {
    const navigate = useNavigate();
    const { apiClient } = useAuth();
    const { selectedJob, setSelectedJob } = useSelectedJob();
    const { setSnack } = useAppState();
    const [jobs, setJobs] = useState<Job[]>([]);
    const [loading, setLoading] = useState(false);
    const [sortField, setSortField] = useState<SortField>('updatedAt');
    const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
    const { jobId } = useParams<{ jobId?: string }>();

    useEffect(() => {
        const getJobs = async () => {
            setLoading(true);
            try {
                const results = await apiClient.getJobs();
                const jobsData: Job[] = results.data || [];
                setJobs(jobsData);
                if (jobId) {
                    const job = jobsData.find(j => j.id === jobId);
                    if (job) {
                        setSelectedJob(job);
                        onSelect?.(job);
                        return;
                    }
                }

                // Auto-select first job if none selected
                if (jobsData.length > 0 && !selectedJob) {
                    const firstJob = sortJobs(jobsData, sortField, sortOrder)[0];
                    setSelectedJob(firstJob);
                    onSelect?.(firstJob);
                }
            } catch (err) {
                setSnack("Failed to load jobs: " + err);
            } finally {
                setLoading(false);
            }
        };

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

    const sortJobs = (jobsList: Job[], field: SortField, order: SortOrder): Job[] => {
        return [...jobsList].sort((a, b) => {
            let aValue: any;
            let bValue: any;

            switch (field) {
                case 'updatedAt':
                    aValue = a.updatedAt?.getTime() || 0;
                    bValue = b.updatedAt?.getTime() || 0;
                    break;
                case 'createdAt':
                    aValue = a.createdAt?.getTime() || 0;
                    bValue = b.createdAt?.getTime() || 0;
                    break;
                case 'company':
                    aValue = a.company?.toLowerCase() || '';
                    bValue = b.company?.toLowerCase() || '';
                    break;
                case 'title':
                    aValue = a.title?.toLowerCase() || '';
                    bValue = b.title?.toLowerCase() || '';
                    break;
                default:
                    return 0;
            }

            if (aValue < bValue) return order === 'asc' ? -1 : 1;
            if (aValue > bValue) return order === 'asc' ? 1 : -1;
            return 0;
        });
    };

    const handleSort = (field: SortField) => {
        if (sortField === field) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortField(field);
            setSortOrder('desc');
        }
    };

    const handleJobSelect = (job: Job) => {
        setSelectedJob(job);
        onSelect?.(job);
        navigate(`/candidate/jobs/${job.id}`);
    };

    const sortedJobs = sortJobs(jobs, sortField, sortOrder);

    const formatDate = (date: Date | undefined) => {
        if (!date) return 'N/A';
        return new Intl.DateTimeFormat('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        }).format(date);
    };

    const getSortIcon = (field: SortField) => {
        if (sortField !== field) return null;
        return sortOrder === 'asc' ? <ArrowUpIcon fontSize="small" /> : <ArrowDownIcon fontSize="small" />;
    };

    return (
        <Box sx={{ display: 'flex', height: '100%', gap: 2, p: 2, position: 'relative' }}>
            {/* Left Panel - Job List */}
            <Paper sx={{ width: '50%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider' }}>
                    <Typography variant="h6" gutterBottom>
                        Jobs ({jobs.length})
                    </Typography>

                    <FormControl size="small" sx={{ minWidth: 200 }}>
                        <InputLabel>Sort by</InputLabel>
                        <Select
                            value={`${sortField}-${sortOrder}`}
                            label="Sort by"
                            onChange={(e) => {
                                const [field, order] = e.target.value.split('-') as [SortField, SortOrder];
                                setSortField(field);
                                setSortOrder(order);
                            }}
                        >
                            <MenuItem value="updatedAt-desc">Updated (Newest)</MenuItem>
                            <MenuItem value="updatedAt-asc">Updated (Oldest)</MenuItem>
                            <MenuItem value="createdAt-desc">Created (Newest)</MenuItem>
                            <MenuItem value="createdAt-asc">Created (Oldest)</MenuItem>
                            <MenuItem value="company-asc">Company (A-Z)</MenuItem>
                            <MenuItem value="company-desc">Company (Z-A)</MenuItem>
                            <MenuItem value="title-asc">Title (A-Z)</MenuItem>
                            <MenuItem value="title-desc">Title (Z-A)</MenuItem>
                        </Select>
                    </FormControl>
                </Box>

                <TableContainer sx={{ flex: 1, overflow: 'auto' }}>
                    <Table stickyHeader size="small">
                        <TableHead>
                            <TableRow>
                                <TableCell
                                    sx={{ cursor: 'pointer', userSelect: 'none' }}
                                    onClick={() => handleSort('company')}
                                >
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <BusinessIcon fontSize="small" />
                                        Company
                                        {getSortIcon('company')}
                                    </Box>
                                </TableCell>
                                <TableCell
                                    sx={{ cursor: 'pointer', userSelect: 'none' }}
                                    onClick={() => handleSort('title')}
                                >
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <WorkIcon fontSize="small" />
                                        Title
                                        {getSortIcon('title')}
                                    </Box>
                                </TableCell>
                                <TableCell
                                    sx={{ cursor: 'pointer', userSelect: 'none' }}
                                    onClick={() => handleSort('updatedAt')}
                                >
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <ScheduleIcon fontSize="small" />
                                        Updated
                                        {getSortIcon('updatedAt')}
                                    </Box>
                                </TableCell>
                                <TableCell>Status</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {sortedJobs.map((job) => (
                                <TableRow
                                    key={job.id}
                                    hover
                                    selected={selectedJob?.id === job.id}
                                    onClick={() => handleJobSelect(job)}
                                    sx={{
                                        cursor: 'pointer',
                                        '&.Mui-selected': {
                                            backgroundColor: 'action.selected',
                                        }
                                    }}
                                >
                                    <TableCell>
                                        <Typography variant="body2" fontWeight="medium">
                                            {job.company || 'N/A'}
                                        </Typography>
                                        {job.details?.location && (
                                            <Typography variant="caption" color="text.secondary">
                                                {job.details.location.city}, {job.details.location.state || job.details.location.country}
                                            </Typography>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        <Typography variant="body2" fontWeight="medium">
                                            {job.title || 'N/A'}
                                        </Typography>
                                        {job.details?.employmentType && (
                                            <Chip
                                                label={job.details.employmentType}
                                                size="small"
                                                variant="outlined"
                                                sx={{ mt: 0.5, fontSize: '0.7rem', height: 20 }}
                                            />
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        <Typography variant="body2">
                                            {formatDate(job.updatedAt)}
                                        </Typography>
                                        {job.createdAt && (
                                            <Typography variant="caption" color="text.secondary">
                                                Created: {formatDate(job.createdAt)}
                                            </Typography>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        <Chip
                                            label={job.details?.isActive ? "Active" : "Inactive"}
                                            color={job.details?.isActive ? "success" : "default"}
                                            size="small"
                                            variant="outlined"
                                        />
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>
            </Paper>

            {/* Right Panel - Job Details */}
            <Paper sx={{ width: '50%', display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider' }}>
                    <Typography variant="h6">
                        Job Details
                    </Typography>
                </Box>

                <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
                    {selectedJob ? (
                        <JobInfo
                            job={selectedJob}
                            variant="all"
                            sx={{
                                border: 'none',
                                boxShadow: 'none',
                                backgroundColor: 'transparent'
                            }}
                        />
                    ) : (
                        <Box sx={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            height: '100%',
                            color: 'text.secondary'
                        }}>
                            <Typography variant="body1">
                                Select a job to view details
                            </Typography>
                        </Box>
                    )}
                </Box>
            </Paper>
        </Box>
    );
};

export { JobViewer };