import React, { useEffect, useState } from 'react';
import {
  Box,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
  FormControl,
  Select,
  MenuItem,
  InputLabel,
  Chip,
  IconButton,
  Dialog,
  AppBar,
  Toolbar,
  useMediaQuery,
  useTheme,
  Slide,
} from '@mui/material';
import {
  KeyboardArrowUp as ArrowUpIcon,
  KeyboardArrowDown as ArrowDownIcon,
  Business as BusinessIcon,
  Work as WorkIcon,
  Schedule as ScheduleIcon,
  Close as CloseIcon,
  ArrowBack as ArrowBackIcon,
} from '@mui/icons-material';
import { TransitionProps } from '@mui/material/transitions';
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 Transition = React.forwardRef(function Transition(
  props: TransitionProps & {
    children: React.ReactElement;
  },
  ref: React.Ref<unknown>
) {
  return <Slide direction="up" ref={ref} {...props} />;
});

const JobViewer: React.FC<JobViewerProps> = ({ onSelect }) => {
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const isSmall = useMediaQuery(theme.breakpoints.down('sm'));

  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 [mobileDialogOpen, setMobileDialogOpen] = useState(false);
  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);
            setMobileDialogOpen(true);
            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);
    setMobileDialogOpen(true);
    navigate(`/candidate/jobs/${job.id}`);
  };

  const handleMobileDialogClose = () => {
    setMobileDialogOpen(false);
  };

  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',
      ...(isMobile ? {} : { year: 'numeric' }),
      ...(isSmall ? {} : { 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" />
    );
  };

  const JobList = () => (
    <Paper
      elevation={isMobile ? 0 : 1}
      sx={{
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        boxShadow: 'none',
        backgroundColor: 'transparent',
      }}
    >
      <Box
        sx={{
          p: isMobile ? 0.5 : 1,
          borderBottom: 1,
          borderColor: 'divider',
          backgroundColor: isMobile ? 'background.paper' : 'inherit',
        }}
      >
        <Typography
          variant={isSmall ? 'subtitle2' : isMobile ? 'subtitle1' : 'h6'}
          gutterBottom
          sx={{ mb: isMobile ? 0.5 : 1, fontWeight: 600 }}
        >
          Jobs ({jobs.length})
        </Typography>

        <FormControl size="small" sx={{ minWidth: isSmall ? 120 : isMobile ? 150 : 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',
          '& .MuiTable-root': {
            tableLayout: isMobile ? 'fixed' : 'auto',
          },
        }}
      >
        <Table stickyHeader size="small">
          <TableHead>
            <TableRow>
              <TableCell
                sx={{
                  cursor: 'pointer',
                  userSelect: 'none',
                  py: isMobile ? 0.25 : 0.5,
                  px: isMobile ? 0.5 : 1,
                  width: isMobile ? '25%' : 'auto',
                  backgroundColor: 'background.paper',
                }}
                onClick={() => handleSort('company')}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <BusinessIcon fontSize={isMobile ? 'small' : 'medium'} />
                  <Typography variant="caption" fontWeight="bold" noWrap>
                    {isSmall ? 'Co.' : isMobile ? 'Company' : 'Company'}
                  </Typography>
                  {getSortIcon('company')}
                </Box>
              </TableCell>
              <TableCell
                sx={{
                  cursor: 'pointer',
                  userSelect: 'none',
                  py: isMobile ? 0.25 : 0.5,
                  px: isMobile ? 0.5 : 1,
                  width: isMobile ? '45%' : 'auto',
                  backgroundColor: 'background.paper',
                }}
                onClick={() => handleSort('title')}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <WorkIcon fontSize={isMobile ? 'small' : 'medium'} />
                  <Typography variant="caption" fontWeight="bold" noWrap>
                    Title
                  </Typography>
                  {getSortIcon('title')}
                </Box>
              </TableCell>
              {!isMobile && (
                <TableCell
                  sx={{
                    cursor: 'pointer',
                    userSelect: 'none',
                    py: 0.5,
                    px: 1,
                    backgroundColor: 'background.paper',
                  }}
                  onClick={() => handleSort('updatedAt')}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <ScheduleIcon fontSize="medium" />
                    <Typography variant="caption" fontWeight="bold">
                      Updated
                    </Typography>
                    {getSortIcon('updatedAt')}
                  </Box>
                </TableCell>
              )}
              <TableCell
                sx={{
                  py: isMobile ? 0.25 : 0.5,
                  px: isMobile ? 0.5 : 1,
                  width: isMobile ? '30%' : 'auto',
                  backgroundColor: 'background.paper',
                }}
              >
                <Typography variant="caption" fontWeight="bold" noWrap>
                  {isMobile ? 'Status' : 'Status'}
                </Typography>
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {sortedJobs.map(job => (
              <TableRow
                key={job.id}
                hover
                selected={selectedJob?.id === job.id}
                onClick={() => handleJobSelect(job)}
                sx={{
                  cursor: 'pointer',
                  height: isMobile ? 48 : 'auto',
                  '&.Mui-selected': {
                    backgroundColor: 'action.selected',
                  },
                  '&:hover': {
                    backgroundColor: 'action.hover',
                  },
                }}
              >
                <TableCell
                  sx={{
                    py: isMobile ? 0.25 : 0.5,
                    px: isMobile ? 0.5 : 1,
                    overflow: 'hidden',
                  }}
                >
                  <Typography
                    variant={isMobile ? 'caption' : 'body2'}
                    fontWeight="medium"
                    noWrap
                    sx={{ fontSize: isMobile ? '0.75rem' : '0.875rem' }}
                  >
                    {job.company || 'N/A'}
                  </Typography>
                  {!isMobile && job.details?.location && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      noWrap
                      sx={{ display: 'block', fontSize: '0.7rem' }}
                    >
                      {job.details.location.city},{' '}
                      {job.details.location.state || job.details.location.country}
                    </Typography>
                  )}
                </TableCell>
                <TableCell
                  sx={{
                    py: isMobile ? 0.25 : 0.5,
                    px: isMobile ? 0.5 : 1,
                    overflow: 'hidden',
                  }}
                >
                  <Typography
                    variant={isMobile ? 'caption' : 'body2'}
                    fontWeight="medium"
                    noWrap
                    sx={{ fontSize: isMobile ? '0.75rem' : '0.875rem' }}
                  >
                    {job.title || 'N/A'}
                  </Typography>
                  {!isMobile && job.details?.employmentType && (
                    <Chip
                      label={job.details.employmentType}
                      size="small"
                      variant="outlined"
                      sx={{
                        mt: 0.25,
                        fontSize: '0.6rem',
                        height: 16,
                        '& .MuiChip-label': { px: 0.5 },
                      }}
                    />
                  )}
                </TableCell>
                {!isMobile && (
                  <TableCell sx={{ py: 0.5, px: 1 }}>
                    <Typography variant="body2" sx={{ fontSize: '0.8rem' }}>
                      {formatDate(job.updatedAt)}
                    </Typography>
                    {job.createdAt && (
                      <Typography
                        variant="caption"
                        color="text.secondary"
                        sx={{ display: 'block', fontSize: '0.7rem' }}
                      >
                        Created: {formatDate(job.createdAt)}
                      </Typography>
                    )}
                  </TableCell>
                )}
                <TableCell
                  sx={{
                    py: isMobile ? 0.25 : 0.5,
                    px: isMobile ? 0.5 : 1,
                    overflow: 'hidden',
                  }}
                >
                  <Chip
                    label={job.details?.isActive ? 'Active' : 'Inactive'}
                    color={job.details?.isActive ? 'success' : 'default'}
                    size="small"
                    variant="outlined"
                    sx={{
                      fontSize: isMobile ? '0.65rem' : '0.7rem',
                      height: isMobile ? 20 : 22,
                      '& .MuiChip-label': {
                        px: isMobile ? 0.5 : 0.75,
                        py: 0,
                      },
                    }}
                  />
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  );

  const JobDetails = ({ inDialog = false }: { inDialog?: boolean }) => (
    <Box
      sx={{
        flex: 1,
        overflow: 'auto',
        p: inDialog ? 1.5 : 0.75,
        height: inDialog ? '100%' : 'auto',
      }}
    >
      {selectedJob ? (
        <JobInfo
          job={selectedJob}
          variant="all"
          sx={{
            border: 'none',
            boxShadow: 'none',
            backgroundColor: 'transparent',
            '& .MuiTypography-h6': {
              fontSize: inDialog ? '1.25rem' : '1.1rem',
            },
          }}
        />
      ) : (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%',
            color: 'text.secondary',
            textAlign: 'center',
            p: 2,
          }}
        >
          <Typography variant="body2">Select a job to view details</Typography>
        </Box>
      )}
    </Box>
  );

  return (
    <Box
      sx={{
        height: '100%',
        p: 0.5,
        backgroundColor: 'background.default',
      }}
    >
      <JobList />

      <Dialog
        fullScreen
        open={mobileDialogOpen}
        onClose={handleMobileDialogClose}
        TransitionComponent={Transition}
        TransitionProps={{ timeout: 300 }}
      >
        <AppBar sx={{ position: 'relative', elevation: 1 }}>
          <Toolbar variant="dense" sx={{ minHeight: 48 }}>
            <IconButton
              edge="start"
              color="inherit"
              onClick={handleMobileDialogClose}
              aria-label="back"
              size="small"
            >
              <ArrowBackIcon />
            </IconButton>
            <Box sx={{ ml: 1, flex: 1, minWidth: 0 }}>
              <Typography variant="h6" component="div" noWrap sx={{ fontSize: '1rem' }}>
                {selectedJob?.title}
              </Typography>
              <Typography
                variant="caption"
                component="div"
                sx={{ color: 'rgba(255, 255, 255, 0.7)' }}
                noWrap
              >
                {selectedJob?.company}
              </Typography>
            </Box>
          </Toolbar>
        </AppBar>
        <JobDetails inDialog />
      </Dialog>
    </Box>
  );
};

export { JobViewer };
