import React, { JSX } from 'react';
import { Box, Link, Typography, Avatar, Grid, SxProps, CardActions, Chip, Stack, CardHeader } from '@mui/material';
import { 
  Card,
  CardContent,
  Divider,
  useTheme,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { useMediaQuery } from '@mui/material';
import { Job, JobFull } from 'types/types';
import { CopyBubble } from "components/CopyBubble";
import { rest } from 'lodash';
import { AIBanner } from 'components/ui/AIBanner';
import { useAuth } from 'hooks/AuthContext';
import { DeleteConfirmation } from '../DeleteConfirmation';
import { Build, CheckCircle, Description, Psychology, Star, Work } from '@mui/icons-material';

interface JobInfoProps {
  job: Job | JobFull;
  sx?: SxProps;
  action?: string;
  elevation?: number;
  variant?: "small" | "normal" | null
};

const JobInfo: React.FC<JobInfoProps> = (props: JobInfoProps) => {
  const { job } = props;
  const { user, apiClient } = useAuth();
    const {
      sx,
      action = '',
      elevation = 1,
      variant = "normal"
    } = props;
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const isAdmin = user?.isAdmin;

  const deleteJob = async (jobId: string | undefined) => {
    if (jobId) {
      await apiClient.deleteJob(jobId);
    }
  }

  if (!job) {
    return <Box>No user loaded.</Box>;
  }

  const renderRequirementSection = (title: string, items: string[] | undefined, icon: JSX.Element, required = false) => {
    if (!items || items.length === 0) return null;

    return (
      <Box sx={{ mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 1.5 }}>
          {icon}
          <Typography variant="subtitle1" sx={{ ml: 1, fontWeight: 600, fontSize: '0.85rem !important'}}>
            {title}
          </Typography>
          {required && <Chip label="Required" size="small" color="error" sx={{ ml: 1, fontSize: '0.75rem !important' }} />}
        </Box>
        <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
          {items.map((item, index) => (
            <Chip
              key={index}
              label={item}
              variant="outlined"
              size="small"
              sx={{ mb: 1, fontSize: '0.75rem !important' }}
            />
          ))}
        </Stack>
      </Box>
    );
  };

  const renderJobRequirements = () => {
    if (!job.requirements) return null;

    return (
      <Card elevation={0} sx={{ m: 0, p: 0, mt: 2,  }}>
        <CardHeader
          title="Job Requirements Analysis"
          avatar={<CheckCircle color="success" />}
          sx={{ p: 0, pb: 1 }}
        />
        <CardContent sx={{ p: 0 }}>
          {renderRequirementSection(
            "Technical Skills (Required)",
            job.requirements.technicalSkills.required,
            <Build color="primary" />,
            true
          )}
          {renderRequirementSection(
            "Technical Skills (Preferred)",
            job.requirements.technicalSkills.preferred,
            <Build color="action" />
          )}
          {renderRequirementSection(
            "Experience Requirements (Required)",
            job.requirements.experienceRequirements.required,
            <Work color="primary" />,
            true
          )}
          {renderRequirementSection(
            "Experience Requirements (Preferred)",
            job.requirements.experienceRequirements.preferred,
            <Work color="action" />
          )}
          {renderRequirementSection(
            "Soft Skills",
            job.requirements.softSkills,
            <Psychology color="secondary" />
          )}
          {renderRequirementSection(
            "Experience",
            job.requirements.experience,
            <Star color="warning" />
          )}
          {renderRequirementSection(
            "Education",
            job.requirements.education,
            <Description color="info" />
          )}
          {renderRequirementSection(
            "Certifications",
            job.requirements.certifications,
            <CheckCircle color="success" />
          )}
          {renderRequirementSection(
            "Preferred Attributes",
            job.requirements.preferredAttributes,
            <Star color="secondary" />
          )}
        </CardContent>
      </Card>
    );
  };

  return (
    <Card 
      elevation={elevation}
      sx={{ 
        display: "flex",
        borderColor: 'transparent',
        borderWidth: 2,
        borderStyle: 'solid',
        transition: 'all 0.3s ease',
        flexDirection: "column",
        ...sx
      }}
      {...rest}
    >
      <CardContent sx={{ display: "flex", flexGrow: 1, p: 3, height: '100%', flexDirection: 'column', alignItems: 'stretch', position: "relative" }}>
        {variant !== "small" && <>
          {'location' in job &&
            <Typography variant="body2" sx={{ mb: 1 }}>
                <strong>Location:</strong> {job.location.city}, {job.location.state || job.location.country}
            </Typography>
            }
          {job.title &&
            <Typography variant="body2" sx={{ mb: 1 }}>
              <strong>Title:</strong> {job.title}
            </Typography>
          }
          {job.company &&
          <Typography variant="body2" sx={{ mb: 1 }}>
              <strong>Company:</strong> {job.company}
          </Typography>
          }
          {job.summary && <Typography variant="body2">
          <strong>Summary:</strong> {job.summary}
          </Typography>
          }
          {job.createdAt && <Typography variant="body2">
          <strong>Created:</strong> {job.createdAt.toISOString()}
          </Typography>
          }
          { job.owner && <Typography variant="body2">
          <strong>Created by:</strong> {job.owner.fullName}
          </Typography>
          }            
        </>}

<Divider/>        
        {renderJobRequirements()}

      </CardContent>
        <CardActions>
          {isAdmin &&
            <DeleteConfirmation
              onDelete={() => { deleteJob(job.id); }}
              sx={{ minWidth: 'auto', px: 2, maxHeight: "min-content", color: "red" }}
              action="delete"
              label="job"
              title="Delete job"
              icon=<DeleteIcon />
              message={`Are you sure you want to delete ${job.id}? This action cannot be undone.`}
            />}
        </CardActions>
    </Card>
  );
};

export { JobInfo };
