import React, { useEffect, useMemo, useState } from "react";

import { Alert, Box, Button, Chip, LinearProgress, Paper, Skeleton, Stack, Typography } from "@mui/material";
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
import PersonOutlineIcon from "@mui/icons-material/PersonOutline";
import UploadFileOutlinedIcon from "@mui/icons-material/UploadFileOutlined";
import WorkOutlineIcon from "@mui/icons-material/WorkOutline";

import { CvVariantSummary, cvBuilderApi } from "../../cvBuilder";
import type { UserOperation } from "../../types";

export type CareerWorkspaceCompleteness = {
  percent: number;
  missing: string[];
};

export type CareerWorkspaceImportRun = {
  id: number;
  status: string;
  errorMessage?: string;
  operation?: UserOperation | null;
};

const activeStatuses = new Set(["queued", "running", "waiting_for_retry", "waiting_for_external_fallback"]);

function isActive(run: CareerWorkspaceImportRun) {
  return run.operation
    ? activeStatuses.has(run.operation.status)
    : run.status === "queued" || run.status === "running";
}

function ActionCard({ title, body, href, label, icon }: {
  title: string;
  body: string;
  href: string;
  label: string;
  icon: React.ReactNode;
}) {
  return (
    <Paper variant="outlined" component="article" sx={{ p: 2, borderRadius: 3, display: "flex", flexDirection: "column", gap: 1.25 }}>
      <Box sx={{ display: "flex", gap: 1, alignItems: "center" }}>
        <Box sx={{ color: "primary.main", display: "flex" }}>{icon}</Box>
        <Typography variant="subtitle1" sx={{ fontWeight: 800 }}>{title}</Typography>
      </Box>
      <Typography variant="body2" color="text.secondary" sx={{ flex: 1 }}>{body}</Typography>
      <Button href={href} variant="text" sx={{ alignSelf: "flex-start", px: 0.5 }}>{label}</Button>
    </Paper>
  );
}

export default function CareerWorkspaceOverview({ completeness, runs, loading, loadError }: {
  completeness: CareerWorkspaceCompleteness | null;
  runs: CareerWorkspaceImportRun[];
  loading: boolean;
  loadError: string | null;
}) {
  const [recentCvs, setRecentCvs] = useState<CvVariantSummary[]>([]);
  const [recentLoading, setRecentLoading] = useState(true);
  const [recentError, setRecentError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    cvBuilderApi.list()
      .then((items) => {
        if (!cancelled) {
          setRecentCvs(Array.isArray(items)
            ? [...items].sort((left, right) => Date.parse(right.updatedAtUtc) - Date.parse(left.updatedAtUtc)).slice(0, 3)
            : []);
          setRecentError(false);
        }
      })
      .catch(() => {
        if (!cancelled) setRecentError(true);
      })
      .finally(() => {
        if (!cancelled) setRecentLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  const importState = useMemo(() => {
    const review = runs.filter((run) => run.status === "pending_review");
    const active = runs.filter(isActive);
    const failed = runs.filter((run) => run.status === "failed" || run.operation?.status === "failed");
    if (review.length > 0) return { severity: "warning" as const, label: "Review imported CV", message: `${review.length} import${review.length === 1 ? " is" : "s are"} waiting for your approval.` };
    if (active.length > 0) return { severity: "info" as const, label: "View CV processing", message: `${active.length} CV import${active.length === 1 ? " is" : "s are"} processing.` };
    if (failed.length > 0) return { severity: "error" as const, label: "Resolve CV import", message: `${failed.length} CV import${failed.length === 1 ? " needs" : "s need"} attention.` };
    return { severity: "success" as const, label: "Import a CV", message: runs.length > 0 ? "Your latest CV import is complete." : "No CV has been imported yet." };
  }, [runs]);

  const isFirstRun = !loading && !recentLoading && !loadError && (completeness?.percent ?? 0) === 0 && runs.length === 0 && recentCvs.length === 0;

  return (
    <Box component="section" aria-labelledby="career-workspace-title" sx={{ display: "grid", gap: 2 }}>
      <Paper sx={{ p: { xs: 2, sm: 2.5 }, borderRadius: 4 }}>
        <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 2, flexWrap: "wrap" }}>
          <Box>
            <Typography id="career-workspace-title" component="h1" variant="h5" sx={{ fontWeight: 900 }}>Career Workspace</Typography>
            <Typography color="text.secondary">Choose what you want to work on next.</Typography>
          </Box>
          <Button variant="contained" startIcon={<DescriptionOutlinedIcon />} href="/career/builder">Open CV Builder</Button>
        </Box>

        {isFirstRun ? <Alert severity="info" sx={{ mt: 2 }}>Start by adding career information manually or importing a CV.</Alert> : null}
        {loadError ? <Alert severity="error" sx={{ mt: 2 }}>Workspace status is unavailable. The profile editor below can retry the request.</Alert> : null}

        <Box sx={{ mt: 2, display: "grid", gridTemplateColumns: { xs: "1fr", md: "minmax(0, 1fr) minmax(0, 1fr)" }, gap: 2 }}>
          <Box aria-label="Profile status" sx={{ p: 2, borderRadius: 3, bgcolor: "background.default", border: "1px solid", borderColor: "divider" }}>
            <Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center" }}>
              <Typography variant="subtitle1" sx={{ fontWeight: 800 }}>Profile completeness</Typography>
              {loading ? <Skeleton width={42} /> : <Typography sx={{ fontWeight: 900 }}>{completeness?.percent ?? 0}%</Typography>}
            </Box>
            <LinearProgress aria-label="Career profile completeness" variant={loading ? "indeterminate" : "determinate"} value={completeness?.percent ?? 0} sx={{ mt: 1, height: 8, borderRadius: 999 }} />
            {!loading && completeness?.missing.length ? (
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>Add next: {completeness.missing.slice(0, 3).join(", ")}</Typography>
            ) : null}
            <Button href="#career-profile-editor" size="small" sx={{ mt: 1, px: 0.5 }}>Improve profile</Button>
          </Box>

          <Alert severity={importState.severity} sx={{ borderRadius: 3, alignItems: "flex-start" }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 800 }}>CV import</Typography>
            <Typography variant="body2">{importState.message}</Typography>
            <Button href="#career-cv-import" color="inherit" size="small" sx={{ mt: 0.75, px: 0.5 }}>{importState.label}</Button>
          </Alert>
        </Box>
      </Paper>

      <Box component="nav" aria-label="Career workspace actions" sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(2, minmax(0, 1fr))", xl: "repeat(4, minmax(0, 1fr))" }, gap: 1.5 }}>
        <ActionCard title="Career profile" body="Add or improve the facts used in every CV." href="#career-profile-editor" label="Edit career profile" icon={<PersonOutlineIcon />} />
        <ActionCard title="Import a CV" body="Extract information, then review every proposed change before applying it." href="#career-cv-import" label={importState.label} icon={<UploadFileOutlinedIcon />} />
        <ActionCard title="General CV" body="Create and manage reusable CV documents from your profile." href="/career/builder" label="Create a general CV" icon={<DescriptionOutlinedIcon />} />
        <ActionCard title="Job-specific CV" body="Open a saved job to tailor and attach a CV for that application." href="/jobs" label="Choose a job" icon={<WorkOutlineIcon />} />
      </Box>

      <Paper component="section" aria-labelledby="recent-cvs-title" sx={{ p: 2, borderRadius: 4 }}>
        <Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
          <Typography id="recent-cvs-title" variant="h6" sx={{ fontWeight: 800 }}>Recent CVs</Typography>
          <Button href="/career/builder" size="small">View all CVs</Button>
        </Box>
        {recentLoading ? (
          <Stack spacing={1} sx={{ mt: 1.5 }}><Skeleton height={32} /><Skeleton height={32} /></Stack>
        ) : recentError ? (
          <Alert severity="warning" sx={{ mt: 1.5 }}>Recent CVs could not be loaded. Open the CV Builder to try again.</Alert>
        ) : recentCvs.length === 0 ? (
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>No CV documents yet.</Typography>
        ) : (
          <Stack spacing={1} sx={{ mt: 1 }}>
            {recentCvs.map((cv) => (
              <Box key={cv.id} sx={{ display: "flex", justifyContent: "space-between", gap: 1, alignItems: "center", flexWrap: "wrap" }}>
                <Box>
                  <Typography variant="body2" sx={{ fontWeight: 700 }}>{cv.name}</Typography>
                  <Typography variant="caption" color="text.secondary">Updated {new Date(cv.updatedAtUtc).toLocaleDateString()}</Typography>
                </Box>
                <Box sx={{ display: "flex", gap: 0.75, alignItems: "center" }}>
                  {cv.jobApplicationId ? <Chip label="Job-specific" size="small" variant="outlined" /> : null}
                  <Button href={`/career/builder/${cv.id}`} size="small">Open</Button>
                </Box>
              </Box>
            ))}
          </Stack>
        )}
      </Paper>
    </Box>
  );
}
