import React, { useEffect, useState } from "react";
import api from "../../../services/api.js";
import { formatStatusLabel, statusBadgeClass } from "../utils/statusBadge.js";

/**
 * @param {{
 *   documentId: number | null,
 *   onClose: () => void,
 *   onRefreshList: () => void
 * }} props
 */
const DocumentDetailDrawer = ({ documentId, onClose, onRefreshList }) => {
  const [doc, setDoc] = useState(null);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const [versionNote, setVersionNote] = useState("");
  const [newVersionLabel, setNewVersionLabel] = useState("");
  const [signNote, setSignNote] = useState({});

  useEffect(() => {
    if (!documentId) {
      setDoc(null);
      return;
    }
    let cancelled = false;
    (async () => {
      setLoading(true);
      setErr("");
      try {
        const { data } = await api.get(`/swi/documents/${documentId}`);
        if (!cancelled) {
          setDoc(data);
          setNewVersionLabel(data.version_label || "");
        }
      } catch (e) {
        if (!cancelled) setErr(e.response?.data?.error || e.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [documentId]);

  if (!documentId) return null;

  const patchStatus = async (status) => {
    try {
      await api.patch(`/swi/documents/${documentId}`, { status });
      onRefreshList();
      const { data } = await api.get(`/swi/documents/${documentId}`);
      setDoc(data);
    } catch (e) {
      setErr(e.response?.data?.error || e.message);
    }
  };

  const addVersion = async (e) => {
    e.preventDefault();
    if (String(newVersionLabel || "").trim() === "") return;
    try {
      await api.post(`/swi/documents/${documentId}/versions`, {
        version_label: newVersionLabel.trim(),
        change_summary: versionNote || "Revision",
        body_text: doc.body_text,
      });
      setVersionNote("");
      onRefreshList();
      const { data } = await api.get(`/swi/documents/${documentId}`);
      setDoc(data);
    } catch (e) {
      setErr(e.response?.data?.error || e.message);
    }
  };

  const uploadFile = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("file", file);
    fd.append("caption", file.name);
    try {
      await api.post(`/swi/documents/${documentId}/media`, fd);
      const { data } = await api.get(`/swi/documents/${documentId}`);
      setDoc(data);
      e.target.value = "";
    } catch (e2) {
      setErr(e2.response?.data?.error || e2.message);
    }
  };

  const signStep = async (stepId, action) => {
    try {
      await api.post(`/swi/approvals/${stepId}/sign`, {
        action,
        signature_note: signNote[stepId] || "",
      });
      onRefreshList();
      const { data } = await api.get(`/swi/documents/${documentId}`);
      setDoc(data);
    } catch (e) {
      setErr(e.response?.data?.error || e.message);
    }
  };

  const formatReviewDate = (v) => {
    if (v == null || v === "") return "—";
    const s = String(v);
    return s.includes("T") ? s.slice(0, 10) : s.length >= 10 ? s.slice(0, 10) : s;
  };

  return (
    <div className="swi-drawer-backdrop" role="presentation" onClick={onClose}>
      <aside
        className="swi-drawer"
        role="dialog"
        aria-modal="true"
        aria-labelledby="swi-document-detail-title"
        aria-label="Document details"
        onClick={(e) => e.stopPropagation()}
      >
        <button type="button" className="swi-btn swi-drawer__close" onClick={onClose}>
          Close
        </button>
        {loading ? <p className="swi-muted">Loading…</p> : null}
        {err ? <div className="swi-error">{err}</div> : null}
        {doc ? (
          <>
            <h2 id="swi-document-detail-title">{doc.title}</h2>
            <p className="swi-muted">
              <span className={statusBadgeClass(doc.status)}>
                {formatStatusLabel(doc.status)}
              </span>{" "}
              · {doc.doc_type} v{doc.version_label}
            </p>
            <p className="swi-muted">
              Contract: {doc.contract_ref || "—"} · Activity: {doc.activity_code || "—"}
            </p>
            <p className="swi-muted">
              Review every {doc.review_cycle_months} mo · Next:{" "}
              {formatReviewDate(doc.next_review_at)}
            </p>

            <div className="swi-inline-actions" style={{ marginTop: "1rem" }}>
              <button type="button" className="swi-btn" onClick={() => patchStatus("draft")}>
                Mark draft
              </button>
              <button
                type="button"
                className="swi-btn"
                onClick={() => patchStatus("in_review")}
              >
                Submit for review
              </button>
              <button
                type="button"
                className="swi-btn"
                onClick={() => patchStatus("published")}
              >
                Publish
              </button>
            </div>

            <div className="swi-subsection">
              <h4>Instruction body</h4>
              <textarea
                className="swi-textarea"
                value={doc.body_text || ""}
                onChange={(e) => setDoc({ ...doc, body_text: e.target.value })}
                onBlur={async (e) => {
                  try {
                    await api.patch(`/swi/documents/${documentId}`, {
                      body_text: e.target.value,
                    });
                    onRefreshList();
                  } catch (ex) {
                    setErr(ex.response?.data?.error || ex.message);
                  }
                }}
              />
            </div>

            <div className="swi-subsection">
              <h4>Multi-level approvals (e-sign)</h4>
              <ul className="swi-version-list">
                {(doc.approvals || []).map((a) => (
                  <li key={a.id}>
                    <strong>
                      {a.step_order}. {a.role_name}
                    </strong>{" "}
                    — {a.assignee_name} — {a.status}
                    {a.status === "pending" ? (
                      <>
                        <input
                          className="swi-input swi-sign-note"
                          placeholder="Signature note (optional)"
                          value={signNote[a.id] || ""}
                          onChange={(e) =>
                            setSignNote((s) => ({ ...s, [a.id]: e.target.value }))
                          }
                        />
                        <div className="swi-inline-actions">
                          <button
                            type="button"
                            className="swi-btn swi-btn--primary"
                            onClick={() => signStep(a.id, "approve")}
                          >
                            Sign approve
                          </button>
                          <button
                            type="button"
                            className="swi-btn swi-btn--danger"
                            onClick={() => signStep(a.id, "reject")}
                          >
                            Reject
                          </button>
                        </div>
                      </>
                    ) : null}
                  </li>
                ))}
              </ul>
            </div>

            <div className="swi-subsection">
              <h4>Version history</h4>
              <ul className="swi-version-list">
                {(doc.versions || []).map((v) => (
                  <li key={v.id}>
                    <strong>{v.version_label}</strong> — {v.change_summary || "—"} (
                    {v.created_at})
                  </li>
                ))}
              </ul>
              <form onSubmit={addVersion}>
                <div className="swi-form-row">
                  <label>New version label</label>
                  <input
                    className="swi-input"
                    value={newVersionLabel}
                    onChange={(e) => setNewVersionLabel(e.target.value)}
                    required
                  />
                </div>
                <div className="swi-form-row">
                  <label>Change summary</label>
                  <input
                    className="swi-input"
                    value={versionNote}
                    onChange={(e) => setVersionNote(e.target.value)}
                  />
                </div>
                <button type="submit" className="swi-btn swi-btn--primary">
                  Record version
                </button>
              </form>
            </div>

            <div className="swi-subsection">
              <h4>Photos / videos</h4>
              <div className="swi-dropzone">
                Upload reference media (mobile or desktop)
                <input type="file" accept="image/*,video/*" onChange={uploadFile} />
              </div>
              <ul className="swi-media-list">
                {(doc.media || []).map((m) => (
                  <li key={m.id}>
                    {m.file_name} ({m.mime_type})
                  </li>
                ))}
              </ul>
            </div>
          </>
        ) : null}
      </aside>
    </div>
  );
};

export default DocumentDetailDrawer;
