import React, { useCallback, useEffect, useState } from "react";
import AssignmentCardGrid from "../../components/swi/assignments/AssignmentCardGrid.jsx";
import AssignmentListTable from "../../components/swi/assignments/AssignmentListTable.jsx";
import AssignmentViewToggle from "../../components/swi/assignments/AssignmentViewToggle.jsx";
import { useAuth } from "../../context/AuthContext.jsx";
import { fetchMyAssignments, startAssignmentWork } from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

const VIEW_STORAGE_KEY = "swi-assignment-list-view";

function readStoredView() {
  try {
    const v = localStorage.getItem(VIEW_STORAGE_KEY);
    return v === "card" ? "card" : "list";
  } catch {
    return "list";
  }
}

export default function AssignmentListPage({ onOpenForm, onViewSubmission }) {
  const { auth } = useAuth();
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [view, setView] = useState(readStoredView);
  const [startingKey, setStartingKey] = useState(null);

  const userName =
    auth?.user?.employee_name ||
    auth?.user?.email_id ||
    auth?.user?.name ||
    "You";

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

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

  const changeView = (next) => {
    setView(next);
    try {
      localStorage.setItem(VIEW_STORAGE_KEY, next);
    } catch {
      /* ignore */
    }
  };

  const handleStartWork = async (documentId, documentNumber) => {
    const key = `${documentId}-${documentNumber}`;
    setStartingKey(key);
    setError("");
    setSuccess("");
    try {
      await startAssignmentWork(documentId, documentNumber);
      await load();
      setSuccess("Status updated to In Progress.");
    } catch (e) {
      setError(getApiErrorMessage(e, "Could not set document to in process."));
    } finally {
      setStartingKey(null);
    }
  };

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

  return (
    <>
      <header className="portal-page-header portal-page-header--solo">
        <div className="portal-page-header__text">
          <h1 className="portal-page-title">Assignment list</h1>
          <p className="portal-page-subtitle">
            All documents assigned to you. Switch between list and card view.
          </p>
        </div>
        <div className="portal-page-header__actions">
          <AssignmentViewToggle view={view} onChange={changeView} />
        </div>
      </header>

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

      <section className="swi-panel swi-assignment-list-panel">
        {!tasks.length ? (
          <p className="swi-muted">No documents assigned to you yet.</p>
        ) : view === "list" ? (
          <AssignmentListTable
            tasks={tasks}
            userName={userName}
            startingKey={startingKey}
            onOpenForm={onOpenForm}
            onViewSubmission={onViewSubmission}
            onStartWork={handleStartWork}
          />
        ) : (
          <AssignmentCardGrid
            tasks={tasks}
            userName={userName}
            startingKey={startingKey}
            onOpenForm={onOpenForm}
            onViewSubmission={onViewSubmission}
            onStartWork={handleStartWork}
          />
        )}
      </section>
    </>
  );
}
