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";
import { useI18n } from "../../i18n/I18nProvider";
import { localizeCompletenessLabel } from "./careerCompletenessLabels";

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, onNavigate }: {
  title: string;
  body: string;
  href: string;
  label: string;
  icon: React.ReactNode;
  onNavigate?: () => void;
}) {
  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}
        onClick={onNavigate ? (event) => { event.preventDefault(); onNavigate(); } : undefined}
        variant="text"
        sx={{ alignSelf: "flex-start", px: 0.5 }}
      >
        {label}
      </Button>
    </Paper>
  );
}

export default function CareerWorkspaceOverview({ completeness, runs, loading, loadError, onNavigate }: {
  completeness: CareerWorkspaceCompleteness | null;
  runs: CareerWorkspaceImportRun[];
  loading: boolean;
  loadError: string | null;
  onNavigate?: (section: "profile" | "import") => void;
}) {
  const { language, t } = useI18n();
  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: t("careerOverviewReviewImport"), message: t(review.length === 1 ? "careerOverviewReviewOne" : "careerOverviewReviewMany", { count: review.length }) };
    if (active.length > 0) return { severity: "info" as const, label: t("careerOverviewViewProcessing"), message: t(active.length === 1 ? "careerOverviewProcessingOne" : "careerOverviewProcessingMany", { count: active.length }) };
    if (failed.length > 0) return { severity: "error" as const, label: t("careerOverviewResolveImport"), message: t(failed.length === 1 ? "careerOverviewFailedOne" : "careerOverviewFailedMany", { count: failed.length }) };
    return { severity: "success" as const, label: t("careerOverviewImportCv"), message: t(runs.length > 0 ? "careerOverviewImportComplete" : "careerOverviewNoImport") };
  }, [runs, t]);

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

  return (
    <Box component="section" aria-labelledby="career-workspace-overview-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-overview-title" component="h2" variant="h5" sx={{ fontWeight: 900 }}>{t("careerWorkspaceOverviewTab")}</Typography>
            <Typography color="text.secondary">{t("careerOverviewSubtitle")}</Typography>
          </Box>
          <Button variant="contained" startIcon={<DescriptionOutlinedIcon />} href="/career/builder">{t("careerOverviewOpenBuilder")}</Button>
        </Box>

        {isFirstRun ? <Alert severity="info" sx={{ mt: 2 }}>{t("careerOverviewFirstRun")}</Alert> : null}
        {loadError ? <Alert severity="error" sx={{ mt: 2 }}>{t("careerOverviewUnavailable")}</Alert> : null}

        <Box sx={{ mt: 2, display: "grid", gridTemplateColumns: { xs: "1fr", md: "minmax(0, 1fr) minmax(0, 1fr)" }, gap: 2 }}>
          <Box aria-label={t("careerOverviewProfileStatus")} 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 }}>{t("careerOverviewCompleteness")}</Typography>
              {loading ? <Skeleton width={42} /> : <Typography sx={{ fontWeight: 900 }}>{completeness?.percent ?? 0}%</Typography>}
            </Box>
            <LinearProgress aria-label={t("careerOverviewCompletenessLabel")} 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 }}>{t("careerOverviewAddNext", { items: completeness.missing.slice(0, 3).map((label) => localizeCompletenessLabel(label, t)).join(", ") })}</Typography>
            ) : null}
            <Button href="/career?section=profile" onClick={onNavigate ? (event) => { event.preventDefault(); onNavigate("profile"); } : undefined} size="small" sx={{ mt: 1, px: 0.5 }}>{t("careerOverviewImproveProfile")}</Button>
          </Box>

          <Alert severity={importState.severity} sx={{ borderRadius: 3, alignItems: "flex-start" }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 800 }}>{t("careerOverviewCvImport")}</Typography>
            <Typography variant="body2">{importState.message}</Typography>
            <Button href="/career?section=import" onClick={onNavigate ? (event) => { event.preventDefault(); onNavigate("import"); } : undefined} color="inherit" size="small" sx={{ mt: 0.75, px: 0.5 }}>{importState.label}</Button>
          </Alert>
        </Box>
      </Paper>

      <Box component="nav" aria-label={t("careerOverviewActions")} sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(2, minmax(0, 1fr))", xl: "repeat(4, minmax(0, 1fr))" }, gap: 1.5 }}>
        <ActionCard title={t("careerOverviewCareerProfile")} body={t("careerOverviewCareerProfileBody")} href="/career?section=profile" onNavigate={onNavigate ? () => onNavigate("profile") : undefined} label={t("careerOverviewEditProfile")} icon={<PersonOutlineIcon />} />
        <ActionCard title={t("careerOverviewImportCv")} body={t("careerOverviewImportBody")} href="/career?section=import" onNavigate={onNavigate ? () => onNavigate("import") : undefined} label={importState.label} icon={<UploadFileOutlinedIcon />} />
        <ActionCard title={t("careerOverviewGeneralCv")} body={t("careerOverviewGeneralCvBody")} href="/career/builder" label={t("careerOverviewCreateGeneralCv")} icon={<DescriptionOutlinedIcon />} />
        <ActionCard title={t("careerOverviewJobCv")} body={t("careerOverviewJobCvBody")} href="/jobs" label={t("careerOverviewChooseJob")} 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 }}>{t("careerOverviewRecentCvs")}</Typography>
          <Button href="/career/builder" size="small">{t("careerOverviewViewAll")}</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 }}>{t("careerOverviewRecentFailed")}</Alert>
        ) : recentCvs.length === 0 ? (
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>{t("careerOverviewNoCvs")}</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">{t("careerOverviewUpdated", { date: new Date(cv.updatedAtUtc).toLocaleDateString(language === "nb" ? "nb-NO" : "en-GB") })}</Typography>
                </Box>
                <Box sx={{ display: "flex", gap: 0.75, alignItems: "center" }}>
                  {cv.jobApplicationId ? <Chip label={t("careerOverviewJobSpecific")} size="small" variant="outlined" /> : null}
                  <Button href={`/career/builder/${cv.id}`} size="small">{t("cvDashboardOpen")}</Button>
                </Box>
              </Box>
            ))}
          </Stack>
        )}
      </Paper>
    </Box>
  );
}
