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

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

import {
  approveAdminSubmission,
  downloadAdminSubmissionDocument,
  downloadAdminSubmissionPdf,
  getAdminSubmissionDetail,
  openAdminSubmissionPdfForPrint,
  rejectAdminSubmission,
  returnAdminSubmission,
  startAdminSubmissionReview
} from "../../services/adminSubmissionService";

const statusLabels = {
  submitted:
    "Awaiting Review",

  under_review:
    "Under Review",

  returned:
    "Returned",

  approved:
    "Approved",

  rejected:
    "Rejected"
};

const correctionStatusLabels = {
  not_required:
    "Not Required",

  awaiting_correction:
    "Awaiting Correction",

  in_progress:
    "Correction in Progress",

  resubmitted:
    "Resubmitted",

  cancelled:
    "Cancelled"
};

const hiddenFields =
  new Set([
    "id",
    "submission_id",
    "staff_id",
    "old_record_id",
    "created_at",
    "updated_at",
    "completed_at",
    "password_hash",
    "storage_path",
    "stored_file_name"
  ]);

const reviewActionConfigurations = {
  start: {
    type:
      "start",

    title:
      "Start HR Review",

    description:
      "Move this submission into active review.",

    confirmText:
      "Start review",

    noteLabel:
      "Review Note",

    notePlaceholder:
      "Add an optional opening note",

    noteRequired:
      false
  },

  approve: {
    type:
      "approve",

    title:
      "Approve Submission",

    description:
      "Confirm that this staff record has passed HR review.",

    confirmText:
      "Approve submission",

    noteLabel:
      "Approval Note",

    notePlaceholder:
      "Add an optional approval note",

    noteRequired:
      false
  },

  return: {
    type:
      "return",

    title:
      "Return for Correction",

    description:
      "The staff member will be allowed to correct and resubmit the form.",

    confirmText:
      "Return submission",

    noteLabel:
      "Reason for Return",

    notePlaceholder:
      "Clearly explain the corrections required",

    noteRequired:
      true
  },

  reject: {
    type:
      "reject",

    title:
      "Reject Submission",

    description:
      "Rejecting the record completes the review and prevents approval.",

    confirmText:
      "Reject submission",

    noteLabel:
      "Reason for Rejection",

    notePlaceholder:
      "Clearly explain why the record is being rejected",

    noteRequired:
      true
  }
};

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

const formatFieldName = (
  fieldName
) => {
  return String(
    fieldName || ""
  )
    .replace(
      /_/g,
      " "
    )
    .replace(
      /\b\w/g,
      (
        character
      ) =>
        character.toUpperCase()
    );
};

const formatValue = (
  value
) => {
  if (
    value === null ||
    value === undefined ||
    value === ""
  ) {
    return "Not provided";
  }

  if (
    value === true ||
    Number(value) === 1
  ) {
    return "Yes";
  }

  if (
    value === false ||
    Number(value) === 0
  ) {
    return "No";
  }

  if (
    typeof value ===
    "object"
  ) {
    try {
      return JSON.stringify(
        value,
        null,
        2
      );
    } catch {
      return String(
        value
      );
    }
  }

  return String(
    value
  );
};

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

  const date =
    new Date(
      value
    );

  if (
    Number.isNaN(
      date.getTime()
    )
  ) {
    return formatValue(
      value
    );
  }

  return new Intl.DateTimeFormat(
    "en-GH",
    {
      dateStyle:
        "medium",

      timeStyle:
        "short"
    }
  ).format(
    date
  );
};

const formatFileSize = (
  bytes
) => {
  const size =
    Number(
      bytes
    );

  if (
    !Number.isFinite(
      size
    ) ||
    size < 1
  ) {
    return "Unknown size";
  }

  if (
    size < 1024
  ) {
    return `${size} B`;
  }

  if (
    size <
    1024 * 1024
  ) {
    return `${(
      size / 1024
    ).toFixed(1)} KB`;
  }

  return `${(
    size /
    (1024 * 1024)
  ).toFixed(1)} MB`;
};

const getRequestErrorMessage = (
  requestError,
  fallbackMessage
) => {
  return (
    requestError.response
      ?.data?.message ||
    requestError.message ||
    fallbackMessage
  );
};

/* =========================================================
   FIELD GRID
   ========================================================= */

const FieldGrid = ({
  record,

  emptyMessage =
    "No information was provided."
}) => {
  const visibleEntries =
    record
      ? Object.entries(
          record
        ).filter(
          ([
            fieldName
          ]) =>
            !hiddenFields.has(
              fieldName
            )
        )
      : [];

  if (
    visibleEntries.length ===
    0
  ) {
    return (
      <div className="admin-review-empty">
        {emptyMessage}
      </div>
    );
  }

  return (
    <div className="admin-review-field-grid">
      {visibleEntries.map(
        ([
          fieldName,
          value
        ]) => (
          <div
            className="admin-review-field"
            key={
              fieldName
            }
          >
            <span>
              {formatFieldName(
                fieldName
              )}
            </span>

            <strong>
              {formatValue(
                value
              )}
            </strong>
          </div>
        )
      )}
    </div>
  );
};

/* =========================================================
   REVIEW SECTION
   ========================================================= */

const ReviewSection = ({
  title,
  description,
  children
}) => {
  return (
    <section className="admin-review-section">
      <div className="admin-review-section__heading">
        <div>
          <h3>
            {title}
          </h3>

          {description && (
            <p>
              {description}
            </p>
          )}
        </div>
      </div>

      {children}
    </section>
  );
};

/* =========================================================
   REPEATING RECORD LIST
   ========================================================= */

const RecordList = ({
  records,
  itemLabel,
  emptyMessage
}) => {
  if (
    records.length === 0
  ) {
    return (
      <div className="admin-review-empty">
        {emptyMessage}
      </div>
    );
  }

  return (
    <div className="admin-review-record-list">
      {records.map(
        (
          record,
          index
        ) => (
          <article
            key={
              record.id ||
              index
            }
            className="admin-review-record-card"
          >
            <h4>
              {itemLabel}{" "}
              {index + 1}
            </h4>

            <FieldGrid
              record={
                record
              }
            />
          </article>
        )
      )}
    </div>
  );
};

/* =========================================================
   CORRECTION HISTORY
   ========================================================= */

const CorrectionHistory = ({
  corrections
}) => {
  if (
    corrections
      .cycles
      .length === 0
  ) {
    return (
      <div className="admin-review-empty">
        This submission has not been returned
        for correction.
      </div>
    );
  }

  return (
    <div className="admin-correction-history">
      {corrections.cycles.map(
        (
          cycle
        ) => {
          const cycleEvents =
            corrections
              .events
              .filter(
                (
                  event
                ) =>
                  Number(
                    event
                      .correction_cycle_id
                  ) ===
                  Number(
                    cycle.id
                  )
              );

          return (
            <article
              key={
                cycle.id
              }
              className="admin-correction-cycle"
            >
              <div className="admin-correction-cycle__heading">
                <div>
                  <span>
                    Correction Cycle
                  </span>

                  <h4>
                    Cycle{" "}
                    {
                      cycle
                        .cycle_number
                    }
                  </h4>
                </div>

                <span className="admin-correction-status">
                  {correctionStatusLabels[
                    cycle
                      .correction_status
                  ] ||
                    formatFieldName(
                      cycle
                        .correction_status
                    )}
                </span>
              </div>

              <div className="admin-correction-detail-grid">
                <div className="admin-correction-detail">
                  <span>
                    Returned By
                  </span>

                  <strong>
                    {cycle
                      .returned_by_name ||
                      "Administrator"}
                  </strong>
                </div>

                <div className="admin-correction-detail">
                  <span>
                    Returned At
                  </span>

                  <strong>
                    {formatDate(
                      cycle
                        .returned_at
                    )}
                  </strong>
                </div>

                <div className="admin-correction-detail">
                  <span>
                    Correction Started
                  </span>

                  <strong>
                    {formatDate(
                      cycle
                        .correction_started_at
                    )}
                  </strong>
                </div>

                <div className="admin-correction-detail">
                  <span>
                    Resubmitted At
                  </span>

                  <strong>
                    {formatDate(
                      cycle
                        .resubmitted_at
                    )}
                  </strong>
                </div>
              </div>

              <div className="admin-correction-message admin-correction-message--hr">
                <strong>
                  HR Return Reason
                </strong>

                <p>
                  {cycle
                    .return_reason ||
                    "No return reason was recorded."}
                </p>
              </div>

              <div className="admin-correction-message admin-correction-message--staff">
                <strong>
                  Staff Response
                </strong>

                <p>
                  {cycle
                    .staff_response_note ||
                    "The staff member has not yet submitted a response."}
                </p>
              </div>

              {cycleEvents.length >
                0 && (
                <div className="admin-correction-events">
                  <h5>
                    Cycle Activity
                  </h5>

                  {cycleEvents.map(
                    (
                      event
                    ) => (
                      <div
                        key={
                          event.id
                        }
                        className="admin-correction-event"
                      >
                        <div>
                          <strong>
                            {formatFieldName(
                              event
                                .action
                            )}
                          </strong>

                          <span>
                            {
                              event
                                .actor_name
                            }
                          </span>
                        </div>

                        <div>
                          <span>
                            {formatDate(
                              event
                                .created_at
                            )}
                          </span>
                        </div>

                        {event
                          .action_note && (
                          <p>
                            {
                              event
                                .action_note
                            }
                          </p>
                        )}
                      </div>
                    )
                  )}
                </div>
              )}
            </article>
          );
        }
      )}
    </div>
  );
};

/* =========================================================
   REVIEW HISTORY
   ========================================================= */

const ReviewHistory = ({
  history
}) => {
  if (
    history.length === 0
  ) {
    return (
      <div className="admin-review-empty">
        No review actions have been recorded.
      </div>
    );
  }

  return (
    <div className="admin-review-timeline">
      {history.map(
        (
          historyItem
        ) => (
          <article
            key={
              historyItem.id
            }
            className="admin-review-timeline__item"
          >
            <div className="admin-review-timeline__marker" />

            <div>
              <div className="admin-review-timeline__heading">
                <strong>
                  {formatFieldName(
                    historyItem
                      .action
                  )}
                </strong>

                <span>
                  {formatDate(
                    historyItem
                      .created_at
                  )}
                </span>
              </div>

              <p>
                {historyItem
                  .action_note ||
                  "No action note was provided."}
              </p>

              <small>
                By{" "}
                {
                  historyItem
                    .admin_user_name
                }
                {" • "}
                {formatFieldName(
                  historyItem
                    .admin_user_role
                )}
              </small>
            </div>
          </article>
        )
      )}
    </div>
  );
};

/* =========================================================
   REVIEW ACTION MODAL
   ========================================================= */

const ReviewActionModal = ({
  actionModal,
  actionLoading,
  actionNote,
  onActionNoteChange,
  onClose,
  onSubmit
}) => {
  if (!actionModal) {
    return null;
  }

  return (
    <div
      className="system-modal-backdrop"
      role="presentation"
      onMouseDown={(
        event
      ) => {
        if (
          event.target ===
          event.currentTarget
        ) {
          onClose();
        }
      }}
    >
      <div
        className="system-modal admin-review-action-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="admin-review-action-title"
      >
        <div className="admin-assignment-modal__heading">
          <div>
            <span>
              HR Review Action
            </span>

            <h3 id="admin-review-action-title">
              {
                actionModal
                  .title
              }
            </h3>

            <p>
              {
                actionModal
                  .description
              }
            </p>
          </div>

          <button
            type="button"
            className="admin-modal-close"
            onClick={
              onClose
            }
            disabled={
              actionLoading
            }
            aria-label="Close review action"
          >
            ×
          </button>
        </div>

        <form
          className="admin-assignment-form"
          onSubmit={
            onSubmit
          }
        >
          <div className="form-group">
            <label htmlFor="review_action_note">
              {
                actionModal
                  .noteLabel
              }

              {!actionModal
                .noteRequired && (
                <span className="optional-label">
                  Optional
                </span>
              )}
            </label>

            <textarea
              id="review_action_note"
              value={
                actionNote
              }
              onChange={(
                event
              ) =>
                onActionNoteChange(
                  event.target.value
                )
              }
              rows={5}
              maxLength={3000}
              disabled={
                actionLoading
              }
              placeholder={
                actionModal
                  .notePlaceholder
              }
              required={
                actionModal
                  .noteRequired
              }
            />
          </div>

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

            <button
              type="submit"
              className={[
                "primary-button",

                actionModal
                  .type ===
                "reject"
                  ? "admin-danger-button"
                  : ""
              ]
                .filter(
                  Boolean
                )
                .join(" ")}
              disabled={
                actionLoading
              }
            >
              {actionLoading
                ? "Processing..."
                : actionModal
                    .confirmText}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

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

const AdminSubmissionReview =
  () => {
    const {
      submissionId
    } =
      useParams();

    const navigate =
      useNavigate();

    const [
      data,
      setData
    ] =
      useState(null);

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

    const [
      actionLoading,
      setActionLoading
    ] =
      useState(false);

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

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

    const [
      actionModal,
      setActionModal
    ] =
      useState(null);

    const [
      actionNote,
      setActionNote
    ] =
      useState("");

    const [
      downloadingDocument,
      setDownloadingDocument
    ] =
      useState(null);

    const [
      recordExportAction,
      setRecordExportAction
    ] =
      useState("");

    /* =====================================================
       LOAD SUBMISSION
       ===================================================== */

    const loadSubmission =
      useCallback(
        async () => {
          try {
            setLoading(
              true
            );

            setError(
              ""
            );

            const result =
              await getAdminSubmissionDetail(
                submissionId
              );

            setData(
              result.data
            );
          } catch (
            requestError
          ) {
            setError(
              getRequestErrorMessage(
                requestError,
                "Unable to load the staff submission."
              )
            );
          } finally {
            setLoading(
              false
            );
          }
        },
        [
          submissionId
        ]
      );

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

    /* =====================================================
       RECORD COMPARISON
       ===================================================== */

    const comparisonRows =
      useMemo(
        () => {
          const oldRecord =
            data
              ?.old_record ||
            {};

          const newRecord =
            data
              ?.new_record ||
            {};

          const fieldNames =
            Array.from(
              new Set([
                ...Object.keys(
                  oldRecord
                ),

                ...Object.keys(
                  newRecord
                )
              ])
            ).filter(
              (
                fieldName
              ) =>
                !hiddenFields.has(
                  fieldName
                )
            );

          return fieldNames
            .map(
              (
                fieldName
              ) => {
                const previousValue =
                  oldRecord[
                    fieldName
                  ];

                const submittedValue =
                  newRecord[
                    fieldName
                  ];

                return {
                  fieldName,
                  previousValue,
                  submittedValue,

                  changed:
                    formatValue(
                      previousValue
                    ) !==
                    formatValue(
                      submittedValue
                    )
                };
              }
            )
            .filter(
              (
                record
              ) =>
                record.changed
            );
        },
        [
          data
        ]
      );

    /* =====================================================
       ACTION MODAL
       ===================================================== */

    const closeActionModal =
      () => {
        if (
          actionLoading
        ) {
          return;
        }

        setActionModal(
          null
        );

        setActionNote(
          ""
        );
      };

    const openActionModal =
      (
        actionType
      ) => {
        const configuration =
          reviewActionConfigurations[
            actionType
          ];

        if (
          !configuration
        ) {
          return;
        }

        setActionModal(
          configuration
        );

        setActionNote(
          ""
        );

        setError(
          ""
        );

        setSuccessMessage(
          ""
        );
      };

    /* =====================================================
       COMPLETE REVIEW ACTION
       ===================================================== */

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

        if (
          !actionModal
        ) {
          return;
        }

        if (
          actionModal
            .noteRequired &&
          actionNote
            .trim()
            .length < 10
        ) {
          setError(
            "Provide a clear reason containing at least 10 characters."
          );

          return;
        }

        try {
          setActionLoading(
            true
          );

          setError(
            ""
          );

          setSuccessMessage(
            ""
          );

          const note =
            actionNote.trim();

          let result =
            null;

          if (
            actionModal.type ===
            "start"
          ) {
            result =
              await startAdminSubmissionReview(
                submissionId,
                {
                  review_note:
                    note
                }
              );
          }

          if (
            actionModal.type ===
            "approve"
          ) {
            result =
              await approveAdminSubmission(
                submissionId,
                {
                  review_note:
                    note
                }
              );
          }

          if (
            actionModal.type ===
            "return"
          ) {
            result =
              await returnAdminSubmission(
                submissionId,
                {
                  return_reason:
                    note
                }
              );
          }

          if (
            actionModal.type ===
            "reject"
          ) {
            result =
              await rejectAdminSubmission(
                submissionId,
                {
                  rejection_reason:
                    note
                }
              );
          }

          setSuccessMessage(
            result
              ?.message ||
              "Review action completed successfully."
          );

          setActionModal(
            null
          );

          setActionNote(
            ""
          );

          await loadSubmission();
        } catch (
          requestError
        ) {
          setError(
            getRequestErrorMessage(
              requestError,
              "Unable to complete the review action."
            )
          );
        } finally {
          setActionLoading(
            false
          );
        }
      };

    /* =====================================================
       DOWNLOAD SUPPORTING DOCUMENT
       ===================================================== */

    const handleDocumentDownload =
      async (
        document
      ) => {
        try {
          setDownloadingDocument(
            document.id
          );

          setError(
            ""
          );

          setSuccessMessage(
            ""
          );

          await downloadAdminSubmissionDocument(
            submissionId,
            document
          );
        } catch (
          requestError
        ) {
          setError(
            getRequestErrorMessage(
              requestError,
              "Unable to download the supporting document."
            )
          );
        } finally {
          setDownloadingDocument(
            null
          );
        }
      };

    /* =====================================================
       DOWNLOAD STAFF RECORD PDF
       ===================================================== */

    const handleDownloadStaffRecord =
      async () => {
        try {
          setRecordExportAction(
            "download"
          );

          setError(
            ""
          );

          setSuccessMessage(
            ""
          );

          await downloadAdminSubmissionPdf(
            submissionId
          );
        } catch (
          requestError
        ) {
          setError(
            getRequestErrorMessage(
              requestError,
              "Unable to download the staff record PDF."
            )
          );
        } finally {
          setRecordExportAction(
            ""
          );
        }
      };

    /* =====================================================
       OPEN STAFF RECORD FOR PRINTING
       ===================================================== */

    const handleOpenPrintableRecord =
      async () => {
        try {
          setRecordExportAction(
            "print"
          );

          setError(
            ""
          );

          setSuccessMessage(
            ""
          );

          await openAdminSubmissionPdfForPrint(
            submissionId
          );
        } catch (
          requestError
        ) {
          setError(
            getRequestErrorMessage(
              requestError,
              "Unable to open the printable staff record."
            )
          );
        } finally {
          setRecordExportAction(
            ""
          );
        }
      };

    /* =====================================================
       LOADING
       ===================================================== */

    if (
      loading
    ) {
      return (
        <div className="admin-page-loading">
          <div className="admin-loading-spinner" />

          <p>
            Loading staff record...
          </p>
        </div>
      );
    }

    /* =====================================================
       LOAD FAILURE
       ===================================================== */

    if (
      !data
    ) {
      return (
        <section className="admin-panel">
          <div className="form-alert form-alert--error">
            {error ||
              "The staff submission could not be loaded."}
          </div>

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

    /* =====================================================
       SAFE DATA
       ===================================================== */

    const submission =
      data.submission ||
      {};

    const staff =
      data.staff ||
      {};

    const sections =
      data.sections ||
      {};

    const history =
      Array.isArray(
        data.history
      )
        ? data.history
        : [];

    const permissions =
      data.permissions ||
      {};

    const corrections = {
      current:
        data.corrections
          ?.current ||
        null,

      cycles:
        Array.isArray(
          data.corrections
            ?.cycles
        )
          ? data.corrections
              .cycles
          : [],

      events:
        Array.isArray(
          data.corrections
            ?.events
        )
          ? data.corrections
              .events
          : []
    };

    const dependents =
      Array.isArray(
        sections.dependents
      )
        ? sections.dependents
        : [];

    const qualifications =
      Array.isArray(
        sections.qualifications
      )
        ? sections.qualifications
        : [];

    const documents =
      Array.isArray(
        sections.documents
      )
        ? sections.documents
        : [];

    const submissionName =
      data.new_record
        ?.full_name ||
      data.old_record
        ?.full_name ||
      "Staff Submission";

    const submittedDate =
      submission
        .resubmitted_at ||
      submission
        .submitted_at;

    const exportBusy =
      Boolean(
        recordExportAction
      );

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

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

    return (
      <div className="admin-review-page">
        {/* =================================================
            REVIEW HEADER
            ================================================= */}

        <section className="admin-review-header">
          <div className="admin-review-header__main">
            <button
              type="button"
              className="admin-review-back-button"
              onClick={() =>
                navigate(
                  "/admin/submissions"
                )
              }
            >
              ← Back to submissions
            </button>

            <span className="admin-review-eyebrow">
              Staff Record Review
            </span>

            <h2>
              {submissionName}
            </h2>

            <div className="admin-review-reference">
              <span>
                Staff ID:{" "}

                <strong>
                  {staff
                    .staff_number ||
                    "Not available"}
                </strong>
              </span>

              <span>
                Reference:{" "}

                <strong>
                  {submission
                    .submission_reference ||
                    "Not available"}
                </strong>
              </span>
            </div>
          </div>

          <div className="admin-review-header__status">
            <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 admin-resubmission-badge--header">
                Resubmitted after correction

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

            <small>
              {submission
                .resubmitted_at
                ? "Resubmitted "
                : "Submitted "}

              {formatDate(
                submittedDate
              )}
            </small>

            {/* =============================================
                INDIVIDUAL STAFF RECORD EXPORT
                ============================================= */}

            <div className="admin-record-export-actions">
              <button
                type="button"
                className="secondary-button"
                onClick={
                  handleOpenPrintableRecord
                }
                disabled={
                  exportBusy
                }
              >
                {recordExportAction ===
                "print"
                  ? "Opening..."
                  : "Open / Print PDF"}
              </button>

              <button
                type="button"
                className="primary-button"
                onClick={
                  handleDownloadStaffRecord
                }
                disabled={
                  exportBusy
                }
              >
                {recordExportAction ===
                "download"
                  ? "Downloading..."
                  : "Download PDF"}
              </button>
            </div>

            {!isApproved && (
              <span className="admin-record-draft-notice">
                This PDF will contain a
                DRAFT - NOT APPROVED watermark.
              </span>
            )}
          </div>
        </section>

        {/* =================================================
            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>
        )}

        {/* =================================================
            SUMMARY
            ================================================= */}

        <section className="admin-review-summary-grid">
          <article>
            <span>
              Submission Status
            </span>

            <strong>
              {statusLabels[
                submission
                  .submission_status
              ] ||
                submission
                  .submission_status}
            </strong>
          </article>

          <article>
            <span>
              Review Status
            </span>

            <strong>
              {formatFieldName(
                submission
                  .review_status ||
                  "pending"
              )}
            </strong>
          </article>

          <article>
            <span>
              Assigned Reviewer
            </span>

            <strong>
              {submission
                .assigned_to_name ||
                "Unassigned"}
            </strong>
          </article>

          <article>
            <span>
              Correction Status
            </span>

            <strong>
              {correctionStatusLabels[
                submission
                  .correction_status
              ] ||
                formatFieldName(
                  submission
                    .correction_status ||
                    "not_required"
                )}
            </strong>
          </article>
        </section>

        {/* =================================================
            REVIEW ACTIONS
            ================================================= */}

        <section className="admin-review-actions">
          {permissions
            .can_start_review && (
            <button
              type="button"
              className="primary-button"
              onClick={() =>
                openActionModal(
                  "start"
                )
              }
            >
              Start review
            </button>
          )}

          {permissions
            .can_approve && (
            <button
              type="button"
              className="admin-review-action admin-review-action--approve"
              onClick={() =>
                openActionModal(
                  "approve"
                )
              }
            >
              Approve
            </button>
          )}

          {permissions
            .can_return && (
            <button
              type="button"
              className="admin-review-action admin-review-action--return"
              onClick={() =>
                openActionModal(
                  "return"
                )
              }
            >
              Return for correction
            </button>
          )}

          {permissions
            .can_reject && (
            <button
              type="button"
              className="admin-review-action admin-review-action--reject"
              onClick={() =>
                openActionModal(
                  "reject"
                )
              }
            >
              Reject
            </button>
          )}
        </section>

        {/* =================================================
            CHANGED RECORDS
            ================================================= */}

        <ReviewSection
          title="Changed Record Information"
          description="Values that differ between the previous HR record and the submitted update."
        >
          {comparisonRows.length ===
          0 ? (
            <div className="admin-review-empty">
              No changed fields were detected.
            </div>
          ) : (
            <div className="admin-table-wrapper">
              <table className="admin-table admin-comparison-table">
                <thead>
                  <tr>
                    <th>
                      Field
                    </th>

                    <th>
                      Previous Record
                    </th>

                    <th>
                      Submitted Record
                    </th>
                  </tr>
                </thead>

                <tbody>
                  {comparisonRows.map(
                    (
                      row
                    ) => (
                      <tr
                        key={
                          row.fieldName
                        }
                      >
                        <td>
                          <strong>
                            {formatFieldName(
                              row
                                .fieldName
                            )}
                          </strong>
                        </td>

                        <td>
                          {formatValue(
                            row
                              .previousValue
                          )}
                        </td>

                        <td className="admin-comparison-changed">
                          {formatValue(
                            row
                              .submittedValue
                          )}
                        </td>
                      </tr>
                    )
                  )}
                </tbody>
              </table>
            </div>
          )}
        </ReviewSection>

        {/* =================================================
            PERSONAL DETAILS
            ================================================= */}

        <ReviewSection
          title="Personal Details"
          description="Personal information supplied by the staff member."
        >
          <FieldGrid
            record={
              sections
                .personal_details
            }
          />
        </ReviewSection>

        {/* =================================================
            EMPLOYMENT DETAILS
            ================================================= */}

        <ReviewSection
          title="Employment Details"
          description="Appointment, grade, designation and duty station information."
        >
          <FieldGrid
            record={
              sections
                .employment_details
            }
          />
        </ReviewSection>

        {/* =================================================
            NEXT OF KIN
            ================================================= */}

        <ReviewSection
          title="Next of Kin"
        >
          <FieldGrid
            record={
              sections
                .next_of_kin
            }
          />
        </ReviewSection>

        {/* =================================================
            DEPENDENTS
            ================================================= */}

        <ReviewSection
          title="Dependents"
        >
          <RecordList
            records={
              dependents
            }
            itemLabel="Dependent"
            emptyMessage="No dependents were provided."
          />
        </ReviewSection>

        {/* =================================================
            EMERGENCY CONTACT
            ================================================= */}

        <ReviewSection
          title="Emergency Contact"
        >
          <FieldGrid
            record={
              sections
                .emergency_contact
            }
          />
        </ReviewSection>

        {/* =================================================
            QUALIFICATIONS
            ================================================= */}

        <ReviewSection
          title="Qualifications"
        >
          <RecordList
            records={
              qualifications
            }
            itemLabel="Qualification"
            emptyMessage="No qualifications were provided."
          />
        </ReviewSection>

        {/* =================================================
            SUPPORTING DOCUMENTS
            ================================================= */}

        <ReviewSection
          title="Supporting Documents"
        >
          {documents.length ===
          0 ? (
            <div className="admin-review-empty">
              No supporting documents were uploaded.
            </div>
          ) : (
            <div className="admin-document-review-list">
              {documents.map(
                (
                  document
                ) => (
                  <article
                    key={
                      document.id
                    }
                    className="admin-document-review-item"
                  >
                    <div>
                      <strong>
                        {document
                          .document_title ||
                          formatFieldName(
                            document
                              .document_type
                          )}
                      </strong>

                      <span>
                        {
                          document
                            .original_file_name
                        }
                      </span>

                      <small>
                        {formatFileSize(
                          document
                            .file_size_bytes
                        )}
                        {" • "}
                        {document
                          .mime_type ||
                          "Document"}
                      </small>
                    </div>

                    <button
                      type="button"
                      className="secondary-button"
                      onClick={() =>
                        handleDocumentDownload(
                          document
                        )
                      }
                      disabled={
                        downloadingDocument ===
                        document.id
                      }
                    >
                      {downloadingDocument ===
                      document.id
                        ? "Downloading..."
                        : "Download"}
                    </button>
                  </article>
                )
              )}
            </div>
          )}
        </ReviewSection>

        {/* =================================================
            DECLARATION
            ================================================= */}

        <ReviewSection
          title="Declaration"
        >
          <FieldGrid
            record={
              sections
                .declaration
            }
          />
        </ReviewSection>

        {/* =================================================
            CORRECTION HISTORY
            ================================================= */}

        <ReviewSection
          title="Correction and Resubmission History"
          description="Every occasion on which HR returned this submission and the staff member responded."
        >
          <CorrectionHistory
            corrections={
              corrections
            }
          />
        </ReviewSection>

        {/* =================================================
            REVIEW HISTORY
            ================================================= */}

        <ReviewSection
          title="Review History"
          description="Permanent record of review and assignment actions."
        >
          <ReviewHistory
            history={
              history
            }
          />
        </ReviewSection>

        {/* =================================================
            REVIEW ACTION MODAL
            ================================================= */}

        <ReviewActionModal
          actionModal={
            actionModal
          }
          actionLoading={
            actionLoading
          }
          actionNote={
            actionNote
          }
          onActionNoteChange={
            setActionNote
          }
          onClose={
            closeActionModal
          }
          onSubmit={
            handleReviewAction
          }
        />
      </div>
    );
  };

export default AdminSubmissionReview;