import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fetchDocuments, fetchLookupTables } from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

function docKey(d) {
  return `${d.document_id}-${d.document_number}`;
}

function formatDate(value) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

function statusLabel(doc) {
  if (doc.document_status_id === 1) return "Opened";
  if (doc.document_status_id === 2) return "Assigned";
  if (doc.document_status_id === 3) return "In Progress";
  if (doc.document_status_id === 4) return "Completed";
  return doc.assigned_to_user_id ? "Assigned" : "Opened";
}

function statusClass(doc) {
  if (doc.document_status_id === 3) return "swi-status-badge--in-progress";
  if (doc.document_status_id === 4) return "swi-status-badge--completed";
  if (doc.document_status_id === 1) return "swi-status-badge--opened";
  if (doc.document_status_id === 2 || doc.assigned_to_user_id) {
    return "swi-status-badge--assigned";
  }
  return "swi-status-badge--opened";
}

/**
 * @param {{
 *   highlightDocumentId?: number | string,
 *   highlightDocumentNumber?: number | string,
 * }} props
 */
export default function AdminDocumentsPage({
  highlightDocumentId,
  highlightDocumentNumber,
}) {
  const [documents, setDocuments] = useState([]);
  const [locationById, setLocationById] = useState(() => new Map());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [query, setQuery] = useState("");
  const highlightRef = useRef(null);

  const highlightKey =
    highlightDocumentId != null && highlightDocumentNumber != null
      ? `${highlightDocumentId}-${highlightDocumentNumber}`
      : null;

  const load = useCallback(async () => {
    setError("");
    const [docs, tables] = await Promise.all([
      fetchDocuments(),
      fetchLookupTables().catch(() => null),
    ]);
    setDocuments(Array.isArray(docs) ? docs : []);
    const map = new Map();
    for (const location of tables?.locations || []) {
      map.set(Number(location.location_id), location.location_name);
    }
    setLocationById(map);
  }, []);

  useEffect(() => {
    load()
      .catch((e) =>
        setError(getApiErrorMessage(e, "Could not load documents."))
      )
      .finally(() => setLoading(false));
  }, [load]);

  useEffect(() => {
    if (!highlightKey || loading) return;
    const frame = requestAnimationFrame(() => {
      highlightRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
    });
    return () => cancelAnimationFrame(frame);
  }, [highlightKey, loading, documents.length]);

  const filteredDocuments = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return documents;
    return documents.filter((d) => {
      const name = (d.document_name || "").toLowerCase();
      const id = String(d.document_id);
      const process = (d.process_name || "").toLowerCase();
      return name.includes(q) || id.includes(q) || process.includes(q);
    });
  }, [documents, query]);

  if (loading) {
    return <p className="swi-muted">Loading documents…</p>;
  }

  return (
    <div className="swi-admin-documents-page">
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">My documents</h1>
          <p className="portal-page-subtitle">
            All SWI documents registered in the library. Assign documents from
            the Assign document page.
          </p>
        </div>
      </header>

      {error ? (
        <div className="swi-error" role="alert">
          {error}
        </div>
      ) : null}

      {highlightKey ? (
        <div className="swi-success" role="status">
          Your new document is highlighted in the list below.
        </div>
      ) : null}

      <div className="swi-admin-assign-toolbar swi-panel">
        <div className="swi-admin-assign-stats">
          <span className="swi-admin-assign-stat">
            <strong>{documents.length}</strong> total
          </span>
        </div>
        <label className="swi-admin-assign-search">
          <span className="visually-hidden">Search documents</span>
          <input
            type="search"
            className="swi-input"
            placeholder="Search by name, ID, or process…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
      </div>

      <section className="swi-panel swi-admin-assign-content">
        {!filteredDocuments.length ? (
          <p className="swi-muted swi-admin-assign-empty">
            {documents.length
              ? "No documents match your search."
              : "No documents yet. Create one on the Create document page."}
          </p>
        ) : (
          <div className="swi-table-wrap swi-admin-assign-table-wrap">
            <table className="swi-table swi-admin-assign-table">
              <thead>
                <tr>
                  <th>Document</th>
                  <th>ID / Rev</th>
                  <th>Plant</th>
                  <th>Process</th>
                  <th>Status</th>
                  <th>Assigned</th>
                </tr>
              </thead>
              <tbody>
                {filteredDocuments.map((d) => {
                  const key = docKey(d);
                  const isHighlighted = key === highlightKey;
                  return (
                    <tr
                      key={key}
                      ref={isHighlighted ? highlightRef : null}
                      className={`swi-admin-assign-table__row${isHighlighted ? " is-highlighted" : ""}`}
                    >
                      <td data-label="Document">
                        <span className="swi-admin-assign-table__name">
                          {d.document_name || "Untitled"}
                        </span>
                      </td>
                      <td data-label="ID / Rev">
                        {d.document_id} · #{d.document_number}
                      </td>
                      <td data-label="Plant">
                        {locationById.get(Number(d.location_id)) ||
                          d.location_name ||
                          "—"}
                      </td>
                      <td data-label="Process">
                        {d.process_name || "—"}
                      </td>
                      <td data-label="Status">
                        <span className={`swi-status-badge ${statusClass(d)}`}>
                          {statusLabel(d)}
                        </span>
                      </td>
                      <td data-label="Assigned">
                        {formatDate(d.assigned_at)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}
