import {
  useCallback,
  useEffect,
  useMemo,
  useState
} from "react";

import {
  useNavigate
} from "react-router-dom";

import {
  useAdminAuth
} from "../../context/AdminAuthContext";

import {
  assignAdminSubmission,
  exportAdminSubmissionPdfBatch,
  exportAdminSubmissionsExcel,
  getAdminReviewers,
  getAdminSubmissions
} from "../../services/adminSubmissionService";

/* =========================================================
   CONSTANTS
   ========================================================= */

const initialPagination = {
  current_page: 1,
  per_page: 10,
  total_records: 0,
  total_pages: 1,
  has_previous_page: false,
  has_next_page: false
};

const statusLabels = {
  submitted: "Awaiting Review",
  under_review: "Under Review",
  returned: "Returned",
  approved: "Approved",
  rejected: "Rejected"
};

const reviewerRoleLabels = {
  super_admin: "Super Administrator",
  hr_admin: "HR Administrator",
  hr_reviewer: "HR Reviewer"
};

/* =========================================================
   FORMAT HELPERS
   ========================================================= */

const formatDate = (dateValue) => {
  if (!dateValue) {
    return "Not available";
  }

  const date = new Date(dateValue);

  if (Number.isNaN(date.getTime())) {
    return "Not available";
  }

  return new Intl.DateTimeFormat(
    "en-GH",
    {
      dateStyle: "medium",
      timeStyle: "short"
    }
  ).format(date);
};

/*
 * Export endpoints return Blob responses.
 * This helper also extracts error messages returned
 * as JSON Blobs by Axios.
 */

const getRequestErrorMessage = async (
  requestError,
  fallbackMessage
) => {
  const responseData =
    requestError.response?.data;

  if (
    typeof Blob !== "undefined" &&
    responseData instanceof Blob
  ) {
    try {
      const responseText =
        await responseData.text();

      if (responseText) {
        try {
          const parsedResponse =
            JSON.parse(responseText);

          return (
            parsedResponse.message ||
            fallbackMessage
          );
        } catch {
          return responseText;
        }
      }
    } catch {
      return fallbackMessage;
    }
  }

  return (
    responseData?.message ||
    requestError.message ||
    fallbackMessage
  );
};

/* =========================================================
   COMPONENT
   ========================================================= */

const AdminSubmissions = () => {
  const navigate = useNavigate();

  const {
    admin
  } = useAdminAuth();

  const canAssign = [
    "super_admin",
    "hr_admin"
  ].includes(admin?.role);

  /* =======================================================
     SUBMISSION DATA
     ======================================================= */

  const [
    submissions,
    setSubmissions
  ] = useState([]);

  const [
    reviewers,
    setReviewers
  ] = useState([]);

  const [
    pagination,
    setPagination
  ] = useState(
    initialPagination
  );

  /* =======================================================
     FILTERS
     ======================================================= */

  const [
    searchInput,
    setSearchInput
  ] = useState("");

  const [
    appliedSearch,
    setAppliedSearch
  ] = useState("");

  const [
    statusFilter,
    setStatusFilter
  ] = useState("");

  const [
    assignmentFilter,
    setAssignmentFilter
  ] = useState("all");

  const [
    reviewerFilter,
    setReviewerFilter
  ] = useState("");

  /* =======================================================
     PAGE STATES
     ======================================================= */

  const [
    loading,
    setLoading
  ] = useState(true);

  const [
    reviewersLoading,
    setReviewersLoading
  ] = useState(false);

  const [
    assigning,
    setAssigning
  ] = useState(false);

  const [
    error,
    setError
  ] = useState("");

  const [
    successMessage,
    setSuccessMessage
  ] = useState("");

  /* =======================================================
     ASSIGNMENT MODAL
     ======================================================= */

  const [
    assignmentModal,
    setAssignmentModal
  ] = useState(null);

  const [
    selectedReviewer,
    setSelectedReviewer
  ] = useState("");

  const [
    assignmentNote,
    setAssignmentNote
  ] = useState("");

  /* =======================================================
     EXPORT STATES
     ======================================================= */

  const [
    selectedSubmissionIds,
    setSelectedSubmissionIds
  ] = useState([]);

  const [
    exportAction,
    setExportAction
  ] = useState("");

  /* =======================================================
     LOAD SUBMISSIONS
     ======================================================= */

  const loadSubmissions =
    useCallback(
      async (
        requestedPage = 1
      ) => {
        try {
          setLoading(true);
          setError("");

          const result =
            await getAdminSubmissions({
              page: requestedPage,
              limit: 10,
              search: appliedSearch,
              status: statusFilter,
              assignment:
                assignmentFilter,
              reviewerId:
                reviewerFilter
            });

          setSubmissions(
            result.data
              .submissions ||
              []
          );

          setPagination({
            ...initialPagination,
            ...result.data
              .pagination
          });

          /*
           * Selections are page-specific.
           * Clear them whenever a new result page loads.
           */

          setSelectedSubmissionIds(
            []
          );
        } catch (
          requestError
        ) {
          setError(
            await getRequestErrorMessage(
              requestError,
              "Unable to load staff submissions."
            )
          );

          setSubmissions([]);
          setSelectedSubmissionIds([]);
        } finally {
          setLoading(false);
        }
      },
      [
        appliedSearch,
        statusFilter,
        assignmentFilter,
        reviewerFilter
      ]
    );

  /* =======================================================
     LOAD REVIEWERS
     ======================================================= */

  const loadReviewers =
    useCallback(
      async () => {
        if (!canAssign) {
          return;
        }

        try {
          setReviewersLoading(
            true
          );

          const result =
            await getAdminReviewers();

          setReviewers(
            result.data
              .reviewers ||
              []
          );
        } catch (
          requestError
        ) {
          console.error(
            "Load reviewers error:",
            requestError
          );
        } finally {
          setReviewersLoading(
            false
          );
        }
      },
      [
        canAssign
      ]
    );

  useEffect(
    () => {
      loadSubmissions(1);
    },
    [
      loadSubmissions
    ]
  );

  useEffect(
    () => {
      loadReviewers();
    },
    [
      loadReviewers
    ]
  );

  /* =======================================================
     APPROVED RECORD SELECTION
     ======================================================= */

  const approvedSubmissionIds =
    useMemo(
      () =>
        submissions
          .filter(
            (
              submission
            ) =>
              submission
                .submission_status ===
              "approved"
          )
          .map(
            (
              submission
            ) =>
              Number(
                submission.id
              )
          )
          .filter(
            (
              submissionId
            ) =>
              Number.isInteger(
                submissionId
              ) &&
              submissionId > 0
          ),
      [
        submissions
      ]
    );

  const allApprovedSelected =
    approvedSubmissionIds.length >
      0 &&
    approvedSubmissionIds.every(
      (
        submissionId
      ) =>
        selectedSubmissionIds.includes(
          submissionId
        )
    );

  const selectedApprovedCount =
    selectedSubmissionIds.length;

  /* =======================================================
     SEARCH AND FILTERS
     ======================================================= */

  const handleSearchSubmit = (
    event
  ) => {
    event.preventDefault();

    setSuccessMessage("");
    setError("");

    setAppliedSearch(
      searchInput.trim()
    );
  };

  const handleClearFilters =
    () => {
      setSearchInput("");
      setAppliedSearch("");
      setStatusFilter("");
      setAssignmentFilter("all");
      setReviewerFilter("");
      setSelectedSubmissionIds([]);
      setSuccessMessage("");
      setError("");
    };

  /* =======================================================
     RECORD SELECTION
     ======================================================= */

  const handleToggleSubmission = (
    submissionId
  ) => {
    const normalizedId =
      Number(submissionId);

    if (
      !Number.isInteger(
        normalizedId
      ) ||
      normalizedId < 1
    ) {
      return;
    }

    setSelectedSubmissionIds(
      (
        currentIds
      ) =>
        currentIds.includes(
          normalizedId
        )
          ? currentIds.filter(
              (
                currentId
              ) =>
                currentId !==
                normalizedId
            )
          : [
              ...currentIds,
              normalizedId
            ]
    );
  };

  const handleToggleAllApproved =
    () => {
      setSelectedSubmissionIds(
        allApprovedSelected
          ? []
          : approvedSubmissionIds
      );
    };

  /* =======================================================
     EXCEL EXPORT
     ======================================================= */

  const handleExportExcel =
    async () => {
      try {
        setExportAction(
          "excel"
        );

        setError("");
        setSuccessMessage("");

        await exportAdminSubmissionsExcel({
          search:
            appliedSearch,

          status:
            statusFilter,

          assignment:
            assignmentFilter,

          reviewerId:
            reviewerFilter
        });

        setSuccessMessage(
          "The staff records Excel export was generated successfully."
        );
      } catch (
        requestError
      ) {
        setError(
          await getRequestErrorMessage(
            requestError,
            "Unable to export the staff records workbook."
          )
        );
      } finally {
        setExportAction("");
      }
    };

  /* =======================================================
     APPROVED PDF BATCH EXPORT
     ======================================================= */

  const handleExportSelectedPdfs =
    async () => {
      if (
        selectedSubmissionIds.length ===
        0
      ) {
        setError(
          "Select at least one approved staff record."
        );

        return;
      }

      try {
        setExportAction(
          "pdf"
        );

        setError("");
        setSuccessMessage("");

        await exportAdminSubmissionPdfBatch(
          selectedSubmissionIds
        );

        setSuccessMessage(
          `${selectedSubmissionIds.length} approved staff record PDF(s) were prepared successfully.`
        );

        setSelectedSubmissionIds(
          []
        );
      } catch (
        requestError
      ) {
        setError(
          await getRequestErrorMessage(
            requestError,
            "Unable to export the selected staff-record PDFs."
          )
        );
      } finally {
        setExportAction("");
      }
    };

  /* =======================================================
     ASSIGNMENT MODAL
     ======================================================= */

  const openAssignmentModal = (
    submission
  ) => {
    setAssignmentModal(
      submission
    );

    setSelectedReviewer(
      submission.assigned_to
        ? String(
            submission
              .assigned_to
          )
        : ""
    );

    setAssignmentNote("");
    setError("");
    setSuccessMessage("");
  };

  const closeAssignmentModal =
    () => {
      if (assigning) {
        return;
      }

      setAssignmentModal(
        null
      );

      setSelectedReviewer("");
      setAssignmentNote("");
    };

  const handleAssignmentSubmit =
    async (
      event
    ) => {
      event.preventDefault();

      if (!assignmentModal) {
        return;
      }

      try {
        setAssigning(true);
        setError("");
        setSuccessMessage("");

        const assignedTo =
          selectedReviewer
            ? Number(
                selectedReviewer
              )
            : null;

        const result =
          await assignAdminSubmission(
            assignmentModal.id,
            {
              assigned_to:
                assignedTo,

              assignment_note:
                assignmentNote.trim()
            }
          );

        setSuccessMessage(
          result.message ||
            "Submission assignment updated."
        );

        setAssignmentModal(
          null
        );

        setSelectedReviewer(
          ""
        );

        setAssignmentNote(
          ""
        );

        await Promise.all([
          loadSubmissions(
            pagination
              .current_page
          ),

          loadReviewers()
        ]);
      } catch (
        requestError
      ) {
        setError(
          await getRequestErrorMessage(
            requestError,
            "Unable to update the assignment."
          )
        );
      } finally {
        setAssigning(false);
      }
    };

  const exportBusy =
    Boolean(exportAction);

  /* =======================================================
     RENDER
     ======================================================= */

  return (
    <div className="admin-submissions-page">
      <section className="admin-panel">
        {/* =================================================
            PAGE HEADING AND EXPORT CONTROLS
            ================================================= */}

        <div className="admin-panel__heading admin-submissions-heading">
          <div>
            <h3>
              Staff Submissions
            </h3>

            <p>
              Search, assign, review and export
              staff records submitted to Human
              Resources.
            </p>
          </div>

          <div className="admin-submissions-heading__tools">
            <div className="admin-submission-count">
              <span>
                Total records
              </span>

              <strong>
                {
                  pagination
                    .total_records
                }
              </strong>
            </div>

            <div className="admin-bulk-export-actions">
              <button
                type="button"
                className="secondary-button"
                onClick={
                  handleExportExcel
                }
                disabled={
                  loading ||
                  exportBusy
                }
              >
                {exportAction ===
                "excel"
                  ? "Exporting Excel..."
                  : "Export Excel"}
              </button>

              <button
                type="button"
                className="primary-button"
                onClick={
                  handleExportSelectedPdfs
                }
                disabled={
                  selectedApprovedCount ===
                    0 ||
                  loading ||
                  exportBusy
                }
              >
                {exportAction ===
                "pdf"
                  ? "Preparing PDFs..."
                  : `Export selected PDFs (${selectedApprovedCount})`}
              </button>
            </div>
          </div>
        </div>

        {/* =================================================
            ALERTS
            ================================================= */}

        {error && (
          <div
            className="form-alert form-alert--error"
            role="alert"
          >
            {error}
          </div>
        )}

        {successMessage && (
          <div
            className="form-alert form-alert--success"
            role="status"
          >
            {successMessage}
          </div>
        )}

        {/* =================================================
            FILTERS
            ================================================= */}

        <form
          className="admin-submission-filters"
          onSubmit={
            handleSearchSubmit
          }
        >
          <div className="admin-filter-search">
            <label htmlFor="submission_search">
              Search submissions
            </label>

            <div className="admin-filter-search__field">
              <input
                id="submission_search"
                type="search"
                value={
                  searchInput
                }
                onChange={(
                  event
                ) =>
                  setSearchInput(
                    event.target.value
                  )
                }
                placeholder="Staff name, Staff ID or reference"
              />

              <button
                type="submit"
                className="primary-button"
                disabled={
                  loading ||
                  exportBusy
                }
              >
                Search
              </button>
            </div>
          </div>

          <div className="admin-filter-group">
            <label htmlFor="submission_status">
              Status
            </label>

            <select
              id="submission_status"
              value={
                statusFilter
              }
              onChange={(
                event
              ) => {
                setStatusFilter(
                  event.target.value
                );

                setSuccessMessage("");
                setSelectedSubmissionIds([]);
              }}
              disabled={
                exportBusy
              }
            >
              <option value="">
                All statuses
              </option>

              <option value="submitted">
                Awaiting review
              </option>

              <option value="under_review">
                Under review
              </option>

              <option value="returned">
                Returned
              </option>

              <option value="approved">
                Approved
              </option>

              <option value="rejected">
                Rejected
              </option>
            </select>
          </div>

          {admin?.role !==
            "hr_reviewer" && (
            <div className="admin-filter-group">
              <label htmlFor="assignment_status">
                Assignment
              </label>

              <select
                id="assignment_status"
                value={
                  assignmentFilter
                }
                onChange={(
                  event
                ) => {
                  setAssignmentFilter(
                    event.target.value
                  );

                  setSuccessMessage("");
                  setSelectedSubmissionIds([]);
                }}
                disabled={
                  exportBusy
                }
              >
                <option value="all">
                  All assignments
                </option>

                <option value="assigned">
                  Assigned
                </option>

                <option value="unassigned">
                  Unassigned
                </option>

                <option value="mine">
                  Assigned to me
                </option>
              </select>
            </div>
          )}

          {canAssign && (
            <div className="admin-filter-group">
              <label htmlFor="reviewer_filter">
                Reviewer
              </label>

              <select
                id="reviewer_filter"
                value={
                  reviewerFilter
                }
                onChange={(
                  event
                ) => {
                  setReviewerFilter(
                    event.target.value
                  );

                  setSuccessMessage("");
                  setSelectedSubmissionIds([]);
                }}
                disabled={
                  reviewersLoading ||
                  exportBusy
                }
              >
                <option value="">
                  All reviewers
                </option>

                {reviewers.map(
                  (
                    reviewer
                  ) => (
                    <option
                      key={
                        reviewer.id
                      }
                      value={
                        reviewer.id
                      }
                    >
                      {
                        reviewer
                          .full_name
                      }{" "}
                      ({
                        reviewer
                          .active_assignments
                      })
                    </option>
                  )
                )}
              </select>
            </div>
          )}

          <button
            type="button"
            className="secondary-button admin-clear-filter-button"
            onClick={
              handleClearFilters
            }
            disabled={
              loading ||
              exportBusy
            }
          >
            Clear filters
          </button>
        </form>

        {/* =================================================
            SUBMISSION TABLE
            ================================================= */}

        {loading ? (
          <div className="admin-page-loading admin-page-loading--compact">
            <div className="admin-loading-spinner" />

            <p>
              Loading staff submissions...
            </p>
          </div>
        ) : submissions.length ===
          0 ? (
          <div className="admin-empty-state admin-empty-state--large">
            No staff submissions match the
            selected filters.
          </div>
        ) : (
          <>
            <div className="admin-table-wrapper">
              <table className="admin-table admin-submissions-table">
                <thead>
                  <tr>
                    {/* Approved PDF selection */}

                    <th className="admin-selection-column">
                      <input
                        type="checkbox"
                        checked={
                          allApprovedSelected
                        }
                        onChange={
                          handleToggleAllApproved
                        }
                        disabled={
                          approvedSubmissionIds
                            .length === 0 ||
                          exportBusy
                        }
                        aria-label="Select all approved staff records on this page"
                        title="Select all approved records on this page"
                      />
                    </th>

                    <th>
                      Staff
                    </th>

                    <th>
                      Reference
                    </th>

                    <th>
                      Status
                    </th>

                    <th>
                      Reviewer
                    </th>

                    <th>
                      Submitted
                    </th>

                    <th>
                      Actions
                    </th>
                  </tr>
                </thead>

                <tbody>
                  {submissions.map(
                    (
                      submission
                    ) => {
                      const submissionId =
                        Number(
                          submission.id
                        );

                      const isApproved =
                        submission
                          .submission_status ===
                        "approved";

                      const isSelected =
                        selectedSubmissionIds.includes(
                          submissionId
                        );

                      return (
                        <tr
                          key={
                            submission.id
                          }
                        >
                          {/* Approved record selection */}

                          <td className="admin-selection-column">
                            <input
                              type="checkbox"
                              checked={
                                isSelected
                              }
                              onChange={() =>
                                handleToggleSubmission(
                                  submissionId
                                )
                              }
                              disabled={
                                !isApproved ||
                                exportBusy
                              }
                              title={
                                isApproved
                                  ? "Select this official staff record"
                                  : "Only approved records can be included in an official PDF batch"
                              }
                              aria-label={
                                isApproved
                                  ? `Select ${submission.full_name || "staff record"}`
                                  : `${submission.full_name || "Staff record"} is not approved`
                              }
                            />
                          </td>

                          <td>
                            <strong>
                              {
                                submission
                                  .full_name
                              }
                            </strong>

                            <span className="admin-table-subtext">
                              Staff ID:{" "}
                              {
                                submission
                                  .staff_number
                              }
                            </span>
                          </td>

                          <td>
                            <span className="admin-reference-value">
                              {
                                submission
                                  .submission_reference
                              }
                            </span>
                          </td>

                          <td>
                            <div className="admin-submission-status-cell">
                              <span
                                className={`admin-status admin-status--${submission.submission_status}`}
                              >
                                {statusLabels[
                                  submission
                                    .submission_status
                                ] ||
                                  submission
                                    .submission_status}
                              </span>

                              {submission
                                .correction_status ===
                                "resubmitted" && (
                                <span className="admin-resubmission-badge">
                                  Resubmitted

                                  {Number(
                                    submission
                                      .return_count
                                  ) > 0
                                    ? ` · Cycle ${submission.return_count}`
                                    : ""}
                                </span>
                              )}
                            </div>
                          </td>

                          <td>
                            {submission
                              .assigned_to_name ? (
                              <div className="admin-assigned-reviewer">
                                <strong>
                                  {
                                    submission
                                      .assigned_to_name
                                  }
                                </strong>

                                <span>
                                  {
                                    submission
                                      .assigned_to_email
                                  }
                                </span>
                              </div>
                            ) : (
                              <span className="admin-unassigned-label">
                                Unassigned
                              </span>
                            )}
                          </td>

                          <td>
                            {formatDate(
                              submission
                                .resubmitted_at ||
                              submission
                                .submitted_at
                            )}

                            {submission
                              .resubmitted_at && (
                              <span className="admin-table-subtext">
                                Correction resubmission
                              </span>
                            )}
                          </td>

                          <td>
                            <div className="admin-table-actions">
                              <button
                                type="button"
                                className="admin-action-button"
                                onClick={() =>
                                  navigate(
                                    `/admin/submissions/${submission.id}`
                                  )
                                }
                                disabled={
                                  exportBusy
                                }
                              >
                                Review
                              </button>

                              {canAssign &&
                                ![
                                  "approved",
                                  "rejected"
                                ].includes(
                                  submission
                                    .submission_status
                                ) && (
                                  <button
                                    type="button"
                                    className="admin-action-button admin-action-button--secondary"
                                    onClick={() =>
                                      openAssignmentModal(
                                        submission
                                      )
                                    }
                                    disabled={
                                      exportBusy
                                    }
                                  >
                                    {submission
                                      .assigned_to
                                      ? "Reassign"
                                      : "Assign"}
                                  </button>
                                )}
                            </div>
                          </td>
                        </tr>
                      );
                    }
                  )}
                </tbody>
              </table>
            </div>

            {/* =================================================
                PAGINATION
                ================================================= */}

            <div className="admin-pagination">
              <div>
                Page{" "}

                <strong>
                  {
                    pagination
                      .current_page
                  }
                </strong>

                {" "}of{" "}

                <strong>
                  {
                    pagination
                      .total_pages
                  }
                </strong>
              </div>

              <div className="admin-pagination__actions">
                <button
                  type="button"
                  className="secondary-button"
                  onClick={() =>
                    loadSubmissions(
                      pagination
                        .current_page -
                        1
                    )
                  }
                  disabled={
                    !pagination
                      .has_previous_page ||
                    loading ||
                    exportBusy
                  }
                >
                  Previous
                </button>

                <button
                  type="button"
                  className="secondary-button"
                  onClick={() =>
                    loadSubmissions(
                      pagination
                        .current_page +
                        1
                    )
                  }
                  disabled={
                    !pagination
                      .has_next_page ||
                    loading ||
                    exportBusy
                  }
                >
                  Next
                </button>
              </div>
            </div>
          </>
        )}
      </section>

      {/* ===================================================
          ASSIGNMENT MODAL
          =================================================== */}

      {assignmentModal && (
        <div
          className="system-modal-backdrop"
          role="presentation"
          onMouseDown={(
            event
          ) => {
            if (
              event.target ===
              event.currentTarget
            ) {
              closeAssignmentModal();
            }
          }}
        >
          <div
            className="system-modal admin-assignment-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="assignment-modal-title"
          >
            <div className="admin-assignment-modal__heading">
              <div>
                <span>
                  Review Assignment
                </span>

                <h3 id="assignment-modal-title">
                  Assign Submission
                </h3>

                <p>
                  {
                    assignmentModal
                      .full_name
                  }

                  {" — "}

                  {
                    assignmentModal
                      .submission_reference
                  }
                </p>
              </div>

              <button
                type="button"
                className="admin-modal-close"
                onClick={
                  closeAssignmentModal
                }
                disabled={
                  assigning
                }
                aria-label="Close assignment window"
              >
                ×
              </button>
            </div>

            <form
              className="admin-assignment-form"
              onSubmit={
                handleAssignmentSubmit
              }
            >
              <div className="form-group">
                <label htmlFor="assigned_reviewer">
                  HR Reviewer
                </label>

                <select
                  id="assigned_reviewer"
                  value={
                    selectedReviewer
                  }
                  onChange={(
                    event
                  ) =>
                    setSelectedReviewer(
                      event.target.value
                    )
                  }
                  disabled={
                    assigning
                  }
                >
                  <option value="">
                    Leave unassigned
                  </option>

                  {reviewers.map(
                    (
                      reviewer
                    ) => (
                      <option
                        key={
                          reviewer.id
                        }
                        value={
                          reviewer.id
                        }
                      >
                        {
                          reviewer
                            .full_name
                        }

                        {" — "}

                        {reviewerRoleLabels[
                          reviewer.role
                        ] ||
                          reviewer.role}

                        {" "}(
                        {
                          reviewer
                            .active_assignments
                        } active)
                      </option>
                    )
                  )}
                </select>
              </div>

              <div className="form-group">
                <label htmlFor="assignment_note">
                  Assignment Note

                  <span className="optional-label">
                    Optional
                  </span>
                </label>

                <textarea
                  id="assignment_note"
                  value={
                    assignmentNote
                  }
                  onChange={(
                    event
                  ) =>
                    setAssignmentNote(
                      event.target.value
                    )
                  }
                  rows={4}
                  maxLength={150}
                  disabled={
                    assigning
                  }
                  placeholder="Add a brief instruction for the reviewer"
                />
              </div>

              <div className="system-modal__actions">
                <button
                  type="button"
                  className="secondary-button"
                  onClick={
                    closeAssignmentModal
                  }
                  disabled={
                    assigning
                  }
                >
                  Cancel
                </button>

                <button
                  type="submit"
                  className="primary-button"
                  disabled={
                    assigning
                  }
                >
                  {assigning
                    ? "Updating..."
                    : selectedReviewer
                      ? "Assign reviewer"
                      : "Remove assignment"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default AdminSubmissions;