import React, { useState } from "react";

import {
  Box,
  Button,
  Chip,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";

import { api } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import { useViewResource } from "../hooks/useViewResource";
import ViewStateNotice from "../components/ViewStateNotice";

type AuditItem = {
  id: number;
  type: string;
  oldValue?: string | null;
  newValue?: string | null;
  note?: string | null;
  at: string;
  jobApplicationId: number;
  jobTitle?: string | null;
  companyName?: string | null;
  ownerUserId?: string | null;
  ownerEmail?: string | null;
  ownerUserName?: string | null;
};

function canUndo(type: string) {
  return ["StatusChanged", "FollowUpSet", "ResponseUpdated", "Deleted", "Restored"].includes(type);
}

export default function AdminAuditPage() {
  const { toast } = useToast();
  const { language, t } = useI18n();
  const [busyId, setBusyId] = useState<number | null>(null);

  const auditResource = useViewResource(
    async () => {
      const r = await api.get<AuditItem[]>("/admin/audit?take=200");
      return r.data ?? [];
    },
    { initialData: [], errorMessage: t("adminAuditLoadFailed"), deps: [t] },
  );

  const undo = async (e: AuditItem) => {
    if (!canUndo(e.type)) return;
    setBusyId(e.id);
    try {
      const res = await api.post<{ ok: boolean; message: string }>(`/admin/audit/${e.id}/undo`, {});
      toast(res.data?.message || t("adminAuditUndone"), "success");
      await auditResource.reload();
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.response?.data || err?.message || t("adminAuditUndoFailed");
      toast(String(msg), "error");
    } finally {
      setBusyId(null);
    }
  };

  const restore = async (e: AuditItem) => {
    setBusyId(e.id);
    try {
      await api.post(`/jobapplications/${e.jobApplicationId}/restore`, {});
      toast(t("adminAuditRestored"), "success");
      await auditResource.reload();
    } catch (err: any) {
      const msg = err?.response?.data || err?.message || t("adminAuditRestoreFailed");
      toast(String(msg), "error");
    } finally {
      setBusyId(null);
    }
  };

  const rows = auditResource.data;

  return (
    <Paper sx={{ mt: 0, p: 2 }}>
      <Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
        {t("adminAuditTitle")}
      </Typography>
      <Typography sx={{ color: "text.secondary", mb: 2 }}>
        {t("adminAuditSubtitle")}
      </Typography>

      <ViewStateNotice
        loading={auditResource.loading}
        error={auditResource.error}
        title={t("adminAuditLoadFailed")}
        description={t("adminAuditLoadFailedBody")}
        onRetry={auditResource.reload}
      />

      {!auditResource.error ? <TableContainer sx={{ borderRadius: 2, 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 sx={{ width: 165 }}>{t("adminAuditAt")}</TableCell>
              <TableCell sx={{ width: 160 }}>{t("adminAuditType")}</TableCell>
              <TableCell>{t("adminAuditJob")}</TableCell>
              <TableCell sx={{ width: 220 }}>{t("adminAuditUser")}</TableCell>
              <TableCell>{t("adminAuditDetails")}</TableCell>
              <TableCell sx={{ width: 170 }}>{t("adminAuditActions")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {auditResource.loading ? (
              <TableRow>
                <TableCell colSpan={6}>
                  <Typography sx={{ color: "text.secondary" }}>{t("loading")}</Typography>
                </TableCell>
              </TableRow>
            ) : rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6}>
                  <Typography sx={{ color: "text.secondary" }}>{t("adminAuditNoEvents")}</Typography>
                </TableCell>
              </TableRow>
            ) : (
              rows.map((e) => {
                const jobLabel = e.jobTitle || t("adminAuditJobFallback", { id: e.jobApplicationId });
                const ownerLabel = e.ownerEmail || e.ownerUserName || e.ownerUserId || "-";
                const details = e.oldValue || e.newValue ? `${e.oldValue ?? ""} -> ${e.newValue ?? ""}` : "";
                const disabled = busyId === e.id;
                const showRestore = e.type === "Deleted";

                return (
                  <TableRow key={e.id} hover>
                    <TableCell>{e.at ? new Date(e.at).toLocaleString(language === "nb" ? "nb-NO" : "en-GB") : ""}</TableCell>
                    <TableCell>
                      <Chip label={e.type} size="small" variant="outlined" />
                    </TableCell>
                    <TableCell>
                      <Typography sx={{ fontWeight: 800, lineHeight: 1.25 }}>
                        {e.companyName ? `${e.companyName} - ` : ""}
                        {jobLabel}
                      </Typography>
                      <Typography variant="caption" sx={{ color: "text.secondary" }}>
                        jobId={e.jobApplicationId}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography sx={{ fontWeight: 700 }}>{ownerLabel}</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography sx={{ whiteSpace: "pre-wrap", color: "text.secondary" }}>
                        {details}
                        {e.note ? `${details ? "\n" : ""}${e.note}` : ""}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
                        {canUndo(e.type) ? (
                          <Button size="small" variant="outlined" disabled={disabled} onClick={() => void undo(e)}>
                            {t("adminAuditUndo")}
                          </Button>
                        ) : null}
                        {showRestore ? (
                          <Button size="small" variant="contained" disabled={disabled} onClick={() => void restore(e)}>
                            {t("adminAuditRestore")}
                          </Button>
                        ) : null}
                      </Box>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer> : null}
    </Paper>
  );
}
