import React, { useCallback, useEffect, useState } from "react";
import { fetchMyAssignments } from "../../services/swiApi.js";
import { isCompleted, statusBadgeClass } from "../../constants/swiDocumentStatus.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

function formatWhen(value) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return String(value);
  return d.toLocaleString();
}

export default function AssignedTasksPage({ onOpenForm, onViewSubmission }) {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const load = useCallback(async () => {
    setError("");
    const rows = await fetchMyAssignments();
    setTasks(rows);
  }, []);

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

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

  return (
    <>
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">My assignments</h1>
          <p className="portal-page-subtitle">
            Documents assigned to you. Open a task to complete the SWI form.
          </p>
        </div>
      </header>

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

      <section className="swi-panel">
        {!tasks.length ? (
          <p className="swi-muted">No documents assigned to you yet.</p>
        ) : (
          <ul className="swi-assign-doc-list">
            {tasks.map((t) => {
              const key = `${t.document_id}-${t.document_number}`;
              const completed = isCompleted(t.document_status_id);
              return (
                <li key={key}>
                  <div className="swi-assign-doc-item swi-assign-doc-item--static">
                    <div className="swi-assign-doc-item__top">
                      <span className="swi-assign-doc-item__title">
                        {t.document_name || "Untitled"}
                      </span>
                      <span
                        className={`swi-status-badge ${statusBadgeClass(t.document_status_id)}`}
                      >
                        {t.document_status_name || "Assigned"}
                      </span>
                    </div>
                    <div className="swi-assign-doc-item__meta">
                      <span className="swi-assign-doc-item__pill">
                        ID {t.document_id}
                      </span>
                      <span className="swi-assign-doc-item__pill">
                        #{t.document_number}
                      </span>
                      {t.location_name ? (
                        <span className="swi-assign-doc-item__pill">
                          {t.location_name}
                        </span>
                      ) : null}
                    </div>
                    <p className="swi-muted swi-assign-task-meta">
                      Assigned {formatWhen(t.assigned_at)}
                      {t.process_name ? ` · ${t.process_name}` : ""}
                    </p>
                    <div className="swi-form-actions swi-form-actions--inline">
                      <button
                        type="button"
                        className="swi-btn swi-btn--primary"
                        onClick={() =>
                          onOpenForm(t.document_id, t.document_number)
                        }
                      >
                        {completed ? "Edit forms" : "Fill form"}
                      </button>
                      <button
                        type="button"
                        className="swi-btn"
                        onClick={() =>
                          onViewSubmission(t.document_id, t.document_number)
                        }
                      >
                        View submission
                      </button>
                    </div>
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </section>
    </>
  );
}
