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

import {
  Alert,
  Box,
  Button,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  IconButton,
  InputLabel,
  LinearProgress,
  MenuItem,
  Select,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";

import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import DriveFileRenameOutlineIcon from "@mui/icons-material/DriveFileRenameOutline";
import DownloadIcon from "@mui/icons-material/Download";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";

import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import { useDialogActions } from "../dialogs";

interface AttachmentItem {
  id: number;
  fileName: string;
  uploadDate: string;
  fileType: string;
  fileSize: number;
  purpose?: string | null;
  useForAi: boolean;
}

function fmtSize(n: number) {
  if (!n) return "";
  const kb = n / 1024;
  if (kb < 1024) return `${kb.toFixed(0)} KB`;
  return `${(kb / 1024).toFixed(1)} MB`;
}

function isImageType(t: string) {
  return (t || "").toLowerCase().startsWith("image/");
}

function isPdfType(t: string) {
  return (t || "").toLowerCase() === "application/pdf";
}

function guessKind(fileName: string): string {
  const n = (fileName || "").toLowerCase();
  if (n.includes("cover")) return "cover-letter";
  if (n.includes("resume") || n.includes("résumé") || n.includes(" cv") || n.endsWith("cv.pdf")) return "resume";
  if (n.includes("portfolio")) return "portfolio";
  if (n.includes("case") || n.includes("sample")) return "case-study";
  if (n.includes("cert")) return "certificate";
  return "other";
}

function purposeLabel(purpose: string | null | undefined, t: (key: any) => string) {
  switch ((purpose || "").trim().toLowerCase()) {
    case "resume": return t("attachmentsPurposeResume");
    case "cover-letter": return t("attachmentsPurposeCoverLetter");
    case "portfolio": return t("attachmentsPurposePortfolio");
    case "case-study": return t("attachmentsPurposeCaseStudy");
    case "certificate": return t("attachmentsPurposeCertificate");
    default: return t("attachmentsPurposeOther");
  }
}

export default function Attachments({ jobId }: { jobId: number }) {
  const { toast } = useToast();
  const { t } = useI18n();
  const { confirmAction, promptForValue } = useDialogActions();
  const [items, setItems] = useState<AttachmentItem[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [preview, setPreview] = useState<{ url: string; type: string; name: string } | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const load = useCallback(async () => {
    try {
      const res = await api.get<AttachmentItem[]>(`/attachments/${jobId}`);
      setItems(res.data);
    } catch {
      // non-fatal
    }
  }, [jobId]);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    return () => {
      if (preview?.url) URL.revokeObjectURL(preview.url);
    };
  }, [preview?.url]);

  const uploadFiles = useCallback(
    async (files: File[]) => {
      if (!files.length) return;

      const data = new FormData();
      files.forEach((f) => data.append("files", f));
      data.append("jobId", jobId.toString());

      setUploading(true);
      try {
        await api.post("/attachments", data, {
          headers: { "Content-Type": "multipart/form-data" },
        });
        toast(files.length === 1 ? t("attachmentsUploadedSingle") : t("attachmentsUploadedMany", { count: files.length }), "success");
        await load();
      } catch (error) {
        toast(getApiErrorMessage(error, t("attachmentsUploadFailed")), "error");
      } finally {
        setUploading(false);
      }
    },
    [jobId, load, t, toast],
  );

  const rename = async (a: AttachmentItem) => {
    const next = await promptForValue(t("attachmentsRenamePrompt"), a.fileName, { title: t("attachmentsRenameTitle"), confirmLabel: t("attachmentsRename") });
    if (!next || next.trim() === a.fileName) return;
    try {
      await api.patch(`/attachments/${a.id}`, { fileName: next.trim() });
      toast(t("attachmentsRenamed"), "success");
      await load();
    } catch (error) {
      toast(getApiErrorMessage(error, t("attachmentsRenameFailed")), "error");
    }
  };

  const updateMetadata = async (a: AttachmentItem, patch: Partial<Pick<AttachmentItem, "purpose" | "useForAi">>) => {
    try {
      await api.patch(`/attachments/${a.id}`, { purpose: patch.purpose ?? a.purpose ?? guessKind(a.fileName), useForAi: patch.useForAi ?? a.useForAi });
      setItems((current) => current.map((item) => item.id === a.id ? { ...item, ...patch } : item));
      toast(t("attachmentsUpdated"), "success");
    } catch (error) {
      toast(getApiErrorMessage(error, t("attachmentsUpdateFailed")), "error");
    }
  };

  const remove = async (a: AttachmentItem) => {
    if (!(await confirmAction(t("attachmentsDeleteConfirm", { name: a.fileName }), { title: t("attachmentsDeleteTitle"), confirmLabel: t("attachmentsDelete"), destructive: true }))) return;
    try {
      await api.delete(`/attachments/${a.id}`);
      toast(t("attachmentsDeleted"), "success");
      await load();
    } catch (error) {
      toast(getApiErrorMessage(error, t("attachmentsDeleteFailed")), "error");
    }
  };

  const upload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files ? Array.from(e.target.files) : [];
    await uploadFiles(files);
    e.target.value = "";
  };

  const getBlobUrl = async (id: number) => {
    const res = await api.get(`/attachments/download/${id}`, { responseType: "blob" });
    const blob: Blob = res.data;
    return URL.createObjectURL(blob);
  };

  const download = async (a: AttachmentItem) => {
    try {
      const url = await getBlobUrl(a.id);
      const link = document.createElement("a");
      link.href = url;
      link.download = a.fileName || `attachment_${a.id}`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.setTimeout(() => URL.revokeObjectURL(url), 5000);
    } catch (error) {
      toast(getApiErrorMessage(error, t("attachmentsDownloadFailed")), "error");
    }
  };

  const openPreview = async (a: AttachmentItem) => {
    try {
      if (preview?.url) URL.revokeObjectURL(preview.url);
      const url = await getBlobUrl(a.id);
      setPreview({ url, type: a.fileType || "", name: a.fileName });
      setPreviewOpen(true);
    } catch (error) {
      toast(getApiErrorMessage(error, t("attachmentsPreviewFailed")), "error");
    }
  };

  const count = useMemo(() => items.length, [items.length]);
  const imageCount = useMemo(() => items.filter((x) => isImageType(x.fileType)).length, [items]);
  const pdfCount = useMemo(() => items.filter((x) => isPdfType(x.fileType)).length, [items]);

  return (
    <Box>
      <Box sx={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 2, mb: 1.5, flexWrap: "wrap" }}>
        <Box>
          <Typography sx={{ fontWeight: 800 }}>{t("attachmentsTitle", { count })}</Typography>
          <Typography variant="body2" sx={{ color: "text.secondary" }}>
            {t("attachmentsSubtitle")}
          </Typography>
          <Box sx={{ display: "flex", gap: 1, mt: 1, flexWrap: "wrap" }}>
            <Chip size="small" label={t("attachmentsImages", { count: imageCount })} variant="outlined" />
            <Chip size="small" label={t("attachmentsPdfs", { count: pdfCount })} variant="outlined" />
            <Chip size="small" label={t("attachmentsMaxSize")} variant="outlined" />
          </Box>
        </Box>
        <Button component="label" size="small" variant="outlined" startIcon={<CloudUploadOutlinedIcon />} disabled={uploading}>
          {uploading ? t("attachmentsUploading") : t("attachmentsUpload")}
          <input ref={fileInputRef} type="file" multiple hidden onChange={upload} />
        </Button>
      </Box>

      <Box
        onDragOver={(e) => {
          e.preventDefault();
          setDragActive(true);
        }}
        onDragEnter={(e) => {
          e.preventDefault();
          setDragActive(true);
        }}
        onDragLeave={(e) => {
          e.preventDefault();
          setDragActive(false);
        }}
        onDrop={(e) => {
          e.preventDefault();
          setDragActive(false);
          void uploadFiles(Array.from(e.dataTransfer.files || []));
        }}
        sx={{
          mb: 2,
          p: 2,
          borderRadius: 3,
          border: "1px dashed",
          borderColor: dragActive ? "primary.main" : "divider",
          backgroundColor: dragActive ? "action.hover" : "background.paper",
          transition: "all 0.2s ease",
          textAlign: "center",
        }}
      >
        <Typography sx={{ fontWeight: 700 }}>{t("attachmentsDragDrop")}</Typography>
        <Typography variant="body2" sx={{ color: "text.secondary", mt: 0.5 }}>
          {t("attachmentsDragDropHelp")}
        </Typography>
        {uploading ? <LinearProgress sx={{ mt: 1.5, borderRadius: 999 }} /> : null}
      </Box>

      <TableContainer sx={{ borderRadius: 3, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>{t("attachmentsName")}</TableCell>
              <TableCell sx={{ width: 140 }}>{t("attachmentsKind")}</TableCell>
              <TableCell sx={{ width: 120 }}>{t("attachmentsType")}</TableCell>
              <TableCell sx={{ width: 90 }}>{t("attachmentsSize")}</TableCell>
              <TableCell sx={{ width: 160 }}>{t("attachmentsPurpose")}</TableCell>
              <TableCell sx={{ width: 110 }}>{t("attachmentsAiUse")}</TableCell>
              <TableCell sx={{ width: 170 }}>{t("attachmentsActions")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {items.map((a) => {
              const canPreview = isImageType(a.fileType) || isPdfType(a.fileType);
              const kind = purposeLabel(a.purpose || guessKind(a.fileName), t);
              return (
                <TableRow key={a.id} hover>
                  <TableCell>
                    <Button size="small" variant="text" onClick={() => void download(a)} sx={{ fontWeight: 800, textTransform: "none" }}>
                      {a.fileName}
                    </Button>
                  </TableCell>
                  <TableCell>{kind}</TableCell>
                  <TableCell sx={{ color: "text.secondary" }}>{a.fileType ? a.fileType.replace("application/", "") : ""}</TableCell>
                  <TableCell sx={{ color: "text.secondary" }}>{a.fileSize ? fmtSize(a.fileSize) : ""}</TableCell>
                  <TableCell sx={{ color: "text.secondary" }}>{a.uploadDate ? new Date(a.uploadDate).toLocaleString() : ""}</TableCell>
                  <TableCell>
                    <FormControl size="small" fullWidth>
                      <InputLabel>{t("attachmentsPurpose")}</InputLabel>
                      <Select value={(a.purpose || guessKind(a.fileName)).toLowerCase()} label={t("attachmentsPurpose")} onChange={(e) => void updateMetadata(a, { purpose: e.target.value })}>
                        <MenuItem value="resume">{t("attachmentsPurposeResume")}</MenuItem>
                        <MenuItem value="cover-letter">{t("attachmentsPurposeCoverLetter")}</MenuItem>
                        <MenuItem value="portfolio">{t("attachmentsPurposePortfolio")}</MenuItem>
                        <MenuItem value="case-study">{t("attachmentsPurposeCaseStudy")}</MenuItem>
                        <MenuItem value="certificate">{t("attachmentsPurposeCertificate")}</MenuItem>
                        <MenuItem value="other">{t("attachmentsPurposeOther")}</MenuItem>
                      </Select>
                    </FormControl>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                      <Switch size="small" checked={Boolean(a.useForAi)} onChange={(_, checked) => void updateMetadata(a, { useForAi: checked })} />
                      <Typography variant="caption" sx={{ color: "text.secondary" }}>{a.useForAi ? t("attachmentsAiEnabled") : t("attachmentsAiDisabled")}</Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: "flex", gap: 0.5, flex: "0 0 auto" }}>
                      {canPreview ? (
                        <IconButton size="small" onClick={() => void openPreview(a)} title={t("attachmentsPreview")}>
                          <VisibilityOutlinedIcon fontSize="small" />
                        </IconButton>
                      ) : null}
                      <IconButton size="small" onClick={() => void download(a)} title={t("attachmentsDownload")}>
                        <DownloadIcon fontSize="small" />
                      </IconButton>
                      <IconButton size="small" onClick={() => void rename(a)} title={t("attachmentsRename")}>
                        <DriveFileRenameOutlineIcon fontSize="small" />
                      </IconButton>
                      <IconButton size="small" onClick={() => void remove(a)} title={t("attachmentsDelete")}>
                        <DeleteOutlineIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </TableCell>
                </TableRow>
              );
            })}

            {items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8}>
                  <Alert severity="info" variant="outlined">
                    {t("attachmentsEmpty")}
                  </Alert>
                </TableCell>
              </TableRow>
            ) : null}
          </TableBody>
        </Table>
      </TableContainer>

      <Dialog open={previewOpen} onClose={() => setPreviewOpen(false)} fullWidth maxWidth="md">
        <DialogTitle>{preview?.name ? t("attachmentsPreviewTitle", { name: preview.name }) : t("attachmentsPreview")}</DialogTitle>
        <DialogContent sx={{ minHeight: 220 }}>
          {!preview ? null : isImageType(preview.type) ? (
            <Box sx={{ display: "flex", justifyContent: "center", py: 1 }}>
              <img src={preview.url} alt={preview.name} style={{ maxWidth: "100%", maxHeight: "70vh", borderRadius: 12 }} />
            </Box>
          ) : isPdfType(preview.type) ? (
            <iframe title="pdf" src={preview.url} style={{ width: "100%", height: 560, border: 0, borderRadius: 12 }} />
          ) : (
            <Typography sx={{ color: "text.secondary" }}>{t("attachmentsNoInlinePreview")}</Typography>
          )}
        </DialogContent>
        <DialogActions>
          {preview ? <Button onClick={() => void download({ id: 0, fileName: preview.name, fileType: preview.type, fileSize: 0, uploadDate: "" } as AttachmentItem)}>{t("attachmentsDownload")}</Button> : null}
          <Button onClick={() => setPreviewOpen(false)}>{t("close")}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
