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

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

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

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

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

const initialOverview = {
  total_submissions: 0,
  unassigned: 0,
  assigned: 0,
  awaiting_review: 0,
  under_review: 0
};

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"
};

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

  const date =
    new Date(value);

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

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

const getReviewerInitials = (
  name
) => {
  const words =
    String(name || "")
      .trim()
      .split(/\s+/)
      .filter(Boolean);

  if (words.length === 0) {
    return "HR";
  }

  return words
    .slice(0, 2)
    .map(
      (word) =>
        word.charAt(0)
          .toUpperCase()
    )
    .join("");
};

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

    const {
      admin
    } = useAdminAuth();

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

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

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

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

    const [
      overview,
      setOverview
    ] = useState(
      initialOverview
    );

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

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

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

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

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

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

    const [
      overviewLoading,
      setOverviewLoading
    ] = useState(true);

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

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

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

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

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

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

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

    const selectedReviewerDetails =
      useMemo(
        () =>
          reviewers.find(
            (reviewer) =>
              String(
                reviewer.id
              ) ===
              String(
                selectedReviewer
              )
          ) || null,
        [
          reviewers,
          selectedReviewer
        ]
      );

    const assignmentUnchanged =
      useMemo(
        () => {
          if (!assignmentModal) {
            return true;
          }

          const currentReviewer =
            assignmentModal
              .assigned_to
              ? String(
                  assignmentModal
                    .assigned_to
                )
              : "";

          return (
            currentReviewer ===
            String(
              selectedReviewer ||
              ""
            )
          );
        },
        [
          assignmentModal,
          selectedReviewer
        ]
      );

    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
            );

            setError(
              requestError.response?.data
                ?.message ||
                requestError.message ||
                "Unable to load HR reviewers."
            );
          } finally {
            setReviewersLoading(
              false
            );
          }
        },
        [
          canAssign
        ]
      );

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

          try {
            setOverviewLoading(
              true
            );

            const [
              totalResult,
              unassignedResult,
              assignedResult,
              awaitingResult,
              underReviewResult
            ] = await Promise.all([
              getAdminSubmissions({
                page: 1,
                limit: 1,
                assignment: "all"
              }),

              getAdminSubmissions({
                page: 1,
                limit: 1,
                assignment:
                  "unassigned"
              }),

              getAdminSubmissions({
                page: 1,
                limit: 1,
                assignment:
                  "assigned"
              }),

              getAdminSubmissions({
                page: 1,
                limit: 1,
                status:
                  "submitted",
                assignment:
                  "all"
              }),

              getAdminSubmissions({
                page: 1,
                limit: 1,
                status:
                  "under_review",
                assignment:
                  "all"
              })
            ]);

            setOverview({
              total_submissions:
                Number(
                  totalResult?.data
                    ?.pagination
                    ?.total_records
                ) || 0,

              unassigned:
                Number(
                  unassignedResult
                    ?.data
                    ?.pagination
                    ?.total_records
                ) || 0,

              assigned:
                Number(
                  assignedResult?.data
                    ?.pagination
                    ?.total_records
                ) || 0,

              awaiting_review:
                Number(
                  awaitingResult?.data
                    ?.pagination
                    ?.total_records
                ) || 0,

              under_review:
                Number(
                  underReviewResult
                    ?.data
                    ?.pagination
                    ?.total_records
                ) || 0
            });
          } catch (
            requestError
          ) {
            console.error(
              "Load assignment overview error:",
              requestError
            );
          } finally {
            setOverviewLoading(
              false
            );
          }
        },
        [
          canAssign
        ]
      );

    const loadSubmissions =
      useCallback(
        async (
          requestedPage = 1
        ) => {
          if (!canAssign) {
            setLoading(false);
            return;
          }

          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
            });
          } catch (
            requestError
          ) {
            console.error(
              "Load review assignments error:",
              requestError
            );

            setError(
              requestError.response?.data
                ?.message ||
                requestError.message ||
                "Unable to load review assignments."
            );

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

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

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

    const refreshWorkspace =
      async () => {
        await Promise.all([
          loadSubmissions(
            pagination
              .current_page
          ),

          loadReviewers(),
          loadOverview()
        ]);
      };

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

      const nextSearch =
        searchInput.trim();

      setSuccessMessage("");

      if (
        nextSearch ===
        appliedSearch
      ) {
        loadSubmissions(1);
        return;
      }

      setAppliedSearch(
        nextSearch
      );
    };

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

    const handleReviewerCardClick = (
      reviewer
    ) => {
      setReviewerFilter(
        String(
          reviewer.id
        )
      );

      setAssignmentFilter(
        "assigned"
      );

      setStatusFilter("");
      setSuccessMessage("");
    };

    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 ||
          assignmentUnchanged
        ) {
          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 ||
              "Review assignment updated successfully."
          );

          setAssignmentModal(
            null
          );

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

          await refreshWorkspace();
        } catch (
          requestError
        ) {
          setError(
            requestError.response?.data
              ?.message ||
              requestError.message ||
              "Unable to update the review assignment."
          );
        } finally {
          setAssigning(false);
        }
      };

    if (!canAssign) {
      return (
        <section className="admin-panel">
          <div className="form-alert form-alert--error">
            Your administrator account does
            not have permission to manage
            review assignments.
          </div>

          <button
            type="button"
            className="secondary-button"
            onClick={() =>
              navigate(
                "/admin/dashboard"
              )
            }
          >
            Back to dashboard
          </button>
        </section>
      );
    }

    return (
      <div className="admin-review-assignments-page">
        <section className="admin-review-assignments-header">
          <div>
            <span className="admin-review-assignments-eyebrow">
              Human Resource Directorate
            </span>

            <h2>
              Review Assignments
            </h2>

            <p>
              Assign staff submissions to HR
              reviewers, monitor reviewer
              workload and redistribute active
              cases when required.
            </p>
          </div>

          <button
            type="button"
            className="secondary-button"
            onClick={
              refreshWorkspace
            }
            disabled={
              loading ||
              reviewersLoading ||
              overviewLoading
            }
          >
            {loading
              ? "Refreshing..."
              : "Refresh assignments"}
          </button>
        </section>

        <section className="admin-assignment-overview">
          <article>
            <span>
              Total Submissions
            </span>

            <strong>
              {overviewLoading
                ? "—"
                : overview
                    .total_submissions}
            </strong>

            <small>
              All records available for HR
              administration.
            </small>
          </article>

          <article>
            <span>
              Unassigned
            </span>

            <strong>
              {overviewLoading
                ? "—"
                : overview
                    .unassigned}
            </strong>

            <small>
              Records that require a reviewer.
            </small>
          </article>

          <article>
            <span>
              Assigned
            </span>

            <strong>
              {overviewLoading
                ? "—"
                : overview
                    .assigned}
            </strong>

            <small>
              Records currently allocated to
              reviewers.
            </small>
          </article>

          <article>
            <span>
              Awaiting Review
            </span>

            <strong>
              {overviewLoading
                ? "—"
                : overview
                    .awaiting_review}
            </strong>

            <small>
              Submitted records awaiting HR
              action.
            </small>
          </article>

          <article>
            <span>
              Under Review
            </span>

            <strong>
              {overviewLoading
                ? "—"
                : overview
                    .under_review}
            </strong>

            <small>
              Records in active review.
            </small>
          </article>
        </section>

        <section className="admin-panel">
          <div className="admin-panel__heading">
            <div>
              <h3>
                Reviewer Workload
              </h3>

              <p>
                Select a reviewer to display
                submissions currently assigned
                to that account.
              </p>
            </div>

            <div className="admin-submission-count">
              <span>
                Active reviewers
              </span>

              <strong>
                {
                  reviewers.length
                }
              </strong>
            </div>
          </div>

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

              <p>
                Loading reviewers...
              </p>
            </div>
          ) : reviewers.length ===
            0 ? (
            <div className="admin-empty-state admin-empty-state--large">
              No active HR reviewers were
              found.
            </div>
          ) : (
            <div className="admin-reviewer-workload-grid">
              {reviewers.map(
                (reviewer) => (
                  <button
                    key={
                      reviewer.id
                    }
                    type="button"
                    className={[
                      "admin-reviewer-workload-card",

                      String(
                        reviewerFilter
                      ) ===
                      String(
                        reviewer.id
                      )
                        ? "admin-reviewer-workload-card--active"
                        : ""
                    ]
                      .filter(Boolean)
                      .join(" ")}
                    onClick={() =>
                      handleReviewerCardClick(
                        reviewer
                      )
                    }
                  >
                    <div className="admin-reviewer-avatar">
                      {getReviewerInitials(
                        reviewer
                          .full_name
                      )}
                    </div>

                    <div className="admin-reviewer-workload-card__details">
                      <strong>
                        {
                          reviewer
                            .full_name
                        }
                      </strong>

                      <span>
                        {reviewerRoleLabels[
                          reviewer.role
                        ] ||
                          reviewer.role}
                      </span>

                      <small>
                        {
                          reviewer
                            .email
                        }
                      </small>
                    </div>

                    <div className="admin-reviewer-workload-card__count">
                      <strong>
                        {
                          reviewer
                            .active_assignments
                        }
                      </strong>

                      <span>
                        Active
                      </span>
                    </div>
                  </button>
                )
              )}
            </div>
          )}
        </section>

        <section className="admin-panel">
          <div className="admin-panel__heading admin-review-assignment-table-heading">
            <div>
              <h3>
                Submission Assignments
              </h3>

              <p>
                Search submitted records and
                assign or reassign them to an
                active HR reviewer.
              </p>
            </div>

            <div className="admin-submission-count">
              <span>
                Matching records
              </span>

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

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

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

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

              <div className="admin-filter-search__field">
                <input
                  id="assignment_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}
                >
                  Search
                </button>
              </div>
            </div>

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

              <select
                id="assignment_status_filter"
                value={
                  statusFilter
                }
                onChange={(event) =>
                  setStatusFilter(
                    event.target.value
                  )
                }
                disabled={loading}
              >
                <option value="">
                  All statuses
                </option>

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

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

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

            <div className="admin-filter-group">
              <label htmlFor="assignment_filter">
                Assignment
              </label>

              <select
                id="assignment_filter"
                value={
                  assignmentFilter
                }
                onChange={(event) =>
                  setAssignmentFilter(
                    event.target.value
                  )
                }
                disabled={loading}
              >
                <option value="all">
                  All assignments
                </option>

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

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

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

            <div className="admin-filter-group">
              <label htmlFor="assignment_reviewer_filter">
                Reviewer
              </label>

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

                  if (
                    event.target.value
                  ) {
                    setAssignmentFilter(
                      "assigned"
                    );
                  }
                }}
                disabled={
                  loading ||
                  reviewersLoading
                }
              >
                <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-review-assignment-clear"
              onClick={
                handleClearFilters
              }
              disabled={loading}
            >
              Clear filters
            </button>
          </form>

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

              <p>
                Loading submission assignments...
              </p>
            </div>
          ) : submissions.length ===
            0 ? (
            <div className="admin-assignment-empty">
              <div className="admin-assignment-empty__icon">
                ✓
              </div>

              <h3>
                No submissions found
              </h3>

              <p>
                No staff submissions match the
                selected assignment filters.
              </p>

              <button
                type="button"
                className="secondary-button"
                onClick={
                  handleClearFilters
                }
              >
                Show all submissions
              </button>
            </div>
          ) : (
            <>
              <div className="admin-table-wrapper">
                <table className="admin-table admin-review-assignment-table">
                  <thead>
                    <tr>
                      <th>
                        Staff Member
                      </th>

                      <th>
                        Submission
                      </th>

                      <th>
                        Status
                      </th>

                      <th>
                        Current Reviewer
                      </th>

                      <th>
                        Submitted
                      </th>

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

                  <tbody>
                    {submissions.map(
                      (submission) => (
                        <tr
                          key={
                            submission.id
                          }
                        >
                          <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>

                            {submission
                              .correction_status ===
                              "resubmitted" && (
                              <span className="admin-resubmission-badge">
                                Resubmitted
                                {Number(
                                  submission
                                    .return_count
                                ) > 0
                                  ? ` · Cycle ${submission.return_count}`
                                  : ""}
                              </span>
                            )}
                          </td>

                          <td>
                            <span
                              className={`admin-status admin-status--${submission.submission_status}`}
                            >
                              {statusLabels[
                                submission
                                  .submission_status
                              ] ||
                                submission
                                  .submission_status}
                            </span>
                          </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={() =>
                                  openAssignmentModal(
                                    submission
                                  )
                                }
                              >
                                {submission
                                  .assigned_to
                                  ? "Reassign"
                                  : "Assign"}
                              </button>

                              <button
                                type="button"
                                className="admin-action-button admin-action-button--secondary"
                                onClick={() =>
                                  navigate(
                                    `/admin/submissions/${submission.id}`
                                  )
                                }
                              >
                                View
                              </button>
                            </div>
                          </td>
                        </tr>
                      )
                    )}
                  </tbody>
                </table>
              </div>

              <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={
                      loading ||
                      !pagination
                        .has_previous_page
                    }
                  >
                    Previous
                  </button>

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

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

                  <h3 id="review-assignment-modal-title">
                    {assignmentModal
                      .assigned_to
                      ? "Reassign Submission"
                      : "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
                }
              >
                {assignmentModal
                  .assigned_to_name && (
                  <div className="admin-current-assignment">
                    <span>
                      Current Reviewer
                    </span>

                    <strong>
                      {
                        assignmentModal
                          .assigned_to_name
                      }
                    </strong>

                    <small>
                      {
                        assignmentModal
                          .assigned_to_email
                      }
                    </small>
                  </div>
                )}

                <div className="form-group">
                  <label htmlFor="review_assignment_reviewer">
                    Select HR Reviewer
                  </label>

                  <select
                    id="review_assignment_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>

                {selectedReviewerDetails && (
                  <div className="admin-selected-reviewer">
                    <div className="admin-reviewer-avatar">
                      {getReviewerInitials(
                        selectedReviewerDetails
                          .full_name
                      )}
                    </div>

                    <div>
                      <strong>
                        {
                          selectedReviewerDetails
                            .full_name
                        }
                      </strong>

                      <span>
                        {reviewerRoleLabels[
                          selectedReviewerDetails
                            .role
                        ] ||
                          selectedReviewerDetails
                            .role}
                      </span>

                      <small>
                        {
                          selectedReviewerDetails
                            .active_assignments
                        }{" "}
                        active assignments
                      </small>
                    </div>
                  </div>
                )}

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

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

                  <textarea
                    id="review_assignment_note"
                    value={
                      assignmentNote
                    }
                    onChange={(event) =>
                      setAssignmentNote(
                        event.target.value
                      )
                    }
                    rows={4}
                    maxLength={150}
                    disabled={assigning}
                    placeholder="Add an instruction or note for the selected reviewer"
                  />

                  <small className="field-help">
                    {
                      assignmentNote
                        .length
                    }
                    /150 characters
                  </small>
                </div>

                {assignmentUnchanged && (
                  <div className="information-banner">
                    Select a different reviewer
                    or remove the current
                    assignment before saving.
                  </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 ||
                      assignmentUnchanged
                    }
                  >
                    {assigning
                      ? "Updating..."
                      : selectedReviewer
                        ? "Save assignment"
                        : "Remove assignment"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    );
  };

export default AdminReviewAssignments;