import {
  useMemo
} from "react";

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

/* =========================================================
   SAFE SESSION STORAGE READER
   ========================================================= */

const readSessionValue = (
  key
) => {
  try {
    const storedValue =
      sessionStorage.getItem(
        key
      );

    return storedValue
      ? JSON.parse(
          storedValue
        )
      : null;
  } catch (error) {
    console.error(
      `Unable to read ${key}:`,
      error
    );

    return null;
  }
};

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

const SubmissionSuccess = () => {
  const location =
    useLocation();

  const navigate =
    useNavigate();

  const verifiedStaff =
    useMemo(
      () =>
        readSessionValue(
          "verifiedStaff"
        ),
      []
    );

  const storedSubmission =
    useMemo(
      () =>
        readSessionValue(
          "staffSubmission"
        ),
      []
    );

  const submissionFromNavigation =
    location.state
      ?.submission ||
    null;

  const submission =
    submissionFromNavigation ||
    storedSubmission ||
    {};

  const staffName =
    verifiedStaff
      ?.full_name ||
    [
      verifiedStaff?.surname,
      verifiedStaff?.first_name,
      verifiedStaff?.middle_name
    ]
      .filter(
        Boolean
      )
      .join(" ") ||
    "Staff Member";

  const staffNumber =
    verifiedStaff
      ?.staff_number ||
    verifiedStaff
      ?.employee_number ||
    "Not available";

  const submissionReference =
    submission
      ?.submission_reference ||
    location.state
      ?.submission_reference ||
    "Not available";

  const submissionStatus =
    submission
      ?.submission_status ||
    location.state
      ?.submission_status ||
    "submitted";

  /* =========================================================
     RETURN TO PORTAL
     ========================================================= */

  const handleReturnToPortal =
    () => {
      sessionStorage.removeItem(
        "staffSubmissionToken"
      );

      sessionStorage.removeItem(
        "verifiedStaff"
      );

      sessionStorage.removeItem(
        "staffSubmission"
      );

      sessionStorage.removeItem(
        "portalCampaign"
      );

      sessionStorage.removeItem(
        "ghanaCardVerificationToken"
      );

      sessionStorage.removeItem(
        "verifiedStaffHint"
      );

      navigate(
        "/staff/access",
        {
          replace: true
        }
      );
    };

  const handlePrint =
    () => {
      window.print();
    };

  return (
    <section className="portal-card portal-card--wide">
      <div className="portal-card__content">
        {/* ===================================================
            SUCCESS HEADING
            =================================================== */}

        <div className="success-heading">
          <span
            className="success-icon"
            aria-hidden="true"
          >
            ✓
          </span>

          <div>
            <p>
              Submission completed
            </p>

            <h2>
              Staff record submitted successfully
            </h2>
          </div>
        </div>

        <div className="information-banner">
          Thank you,{" "}
          <strong>
            {staffName}
          </strong>
          . Your staff record has been submitted
          successfully for Human Resource review.
        </div>

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

        <div className="record-summary">
          <div>
            <span>
              Staff ID
            </span>

            <strong>
              {staffNumber}
            </strong>
          </div>

          <div>
            <span>
              Submission reference
            </span>

            <strong>
              {submissionReference}
            </strong>
          </div>

          <div>
            <span>
              Submission status
            </span>

            <strong className="status-badge">
              {String(
                submissionStatus
              )
                .replace(
                  /_/g,
                  " "
                )}
            </strong>
          </div>
        </div>

        {/* ===================================================
            NEXT STEPS
            =================================================== */}

        <div className="form-roadmap">
          <h3>
            What happens next?
          </h3>

          <ol>
            <li>
              Your submission will be assigned
              to an authorised Human Resource
              reviewer.
            </li>

            <li>
              The reviewer will verify the
              information and supporting
              documents provided.
            </li>

            <li>
              Keep your submission reference
              for future enquiries.
            </li>
          </ol>
        </div>

        <div className="information-banner">
          You can now safely leave this page.
          Submitted information can no longer
          be edited unless it is returned by
          Human Resources.
        </div>

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

        <div className="submission-success-actions">
          <button
            type="button"
            className="primary-button"
            onClick={
              handleReturnToPortal
            }
          >
            Return to staff portal
          </button>

          <button
            type="button"
            className="secondary-button"
            onClick={
              handlePrint
            }
          >
            Print confirmation
          </button>
        </div>
      </div>
    </section>
  );
};

export default SubmissionSuccess;