import {
  useEffect,
  useState
} from "react";

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

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

import {
  getAdminDashboard
} from "../../services/adminDashboardService";

const initialSummary = {
  total_submissions: 0,
  awaiting_review: 0,
  under_review: 0,
  approved: 0,
  returned: 0,
  rejected: 0,
  submitted_today: 0
};

const statusLabels = {
  submitted:
    "Awaiting Review",

  under_review:
    "Under Review",

  approved:
    "Approved",

  returned:
    "Returned",

  rejected:
    "Rejected"
};

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

  const date =
    new Date(dateValue);

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

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

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

  const {
    admin
  } = useAdminAuth();

  const [
    summary,
    setSummary
  ] = useState(
    initialSummary
  );

  const [
    recentSubmissions,
    setRecentSubmissions
  ] = useState([]);

  const [
    reviewerWorkload,
    setReviewerWorkload
  ] = useState([]);

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

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

  useEffect(() => {
    const loadDashboard =
      async () => {
        try {
          setLoading(true);
          setError("");

          const result =
            await getAdminDashboard();

          setSummary({
            ...initialSummary,
            ...result.data.summary
          });

          setRecentSubmissions(
            result.data
              .recent_submissions ||
              []
          );

          setReviewerWorkload(
            result.data
              .reviewer_workload ||
              []
          );
        } catch (requestError) {
          setError(
            requestError.response?.data
              ?.message ||
              requestError.message ||
              "Unable to load the administrator dashboard."
          );
        } finally {
          setLoading(false);
        }
      };

    loadDashboard();
  }, []);

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

        <p>
          Loading dashboard information...
        </p>
      </div>
    );
  }

  return (
    <div className="admin-dashboard">
      <section className="admin-welcome-panel">
        <div>
          <span>
            Welcome back
          </span>

          <h2>
            {admin.full_name}
          </h2>

          <p>
            Review staff submissions and
            manage the personal records update
            exercise from this portal.
          </p>
        </div>

        <div className="admin-today-summary">
          <span>
            Submitted today
          </span>

          <strong>
            {
              summary
                .submitted_today
            }
          </strong>
        </div>
      </section>

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

      <section className="admin-stat-grid">
        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Total submissions
          </span>

          <strong>
            {
              summary
                .total_submissions
            }
          </strong>

          <p>
            All staff records received
          </p>
        </article>

        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Awaiting review
          </span>

          <strong>
            {
              summary
                .awaiting_review
            }
          </strong>

          <p>
            New submissions requiring action
          </p>
        </article>

        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Under review
          </span>

          <strong>
            {
              summary
                .under_review
            }
          </strong>

          <p>
            Reviews currently in progress
          </p>
        </article>

        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Approved
          </span>

          <strong>
            {summary.approved}
          </strong>

          <p>
            Successfully approved records
          </p>
        </article>

        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Returned
          </span>

          <strong>
            {summary.returned}
          </strong>

          <p>
            Returned to staff for correction
          </p>
        </article>

        <article className="admin-stat-card">
          <span className="admin-stat-card__label">
            Rejected
          </span>

          <strong>
            {summary.rejected}
          </strong>

          <p>
            Records rejected after review
          </p>
        </article>
      </section>

      <section className="admin-dashboard-grid">
        <article className="admin-panel admin-panel--wide">
          <div className="admin-panel__heading">
            <div>
              <h3>
                Recent Submissions
              </h3>

              <p>
                Latest staff records submitted
                for HR review.
              </p>
            </div>

            <button
              type="button"
              className="admin-text-button"
              onClick={() =>
                navigate(
                  "/admin/submissions"
                )
              }
            >
              View all
            </button>
          </div>

          {recentSubmissions.length ===
          0 ? (
            <div className="admin-empty-state">
              No submitted staff records are
              available.
            </div>
          ) : (
            <div className="admin-table-wrapper">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>
                      Staff
                    </th>

                    <th>
                      Reference
                    </th>

                    <th>
                      Status
                    </th>

                    <th>
                      Assigned To
                    </th>

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

                <tbody>
                  {recentSubmissions.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>
                          {
                            submission
                              .submission_reference
                          }
                        </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 ||
                            "Unassigned"}
                        </td>

                        <td>
                          {formatDate(
                            submission
                              .submitted_at
                          )}
                        </td>
                      </tr>
                    )
                  )}
                </tbody>
              </table>
            </div>
          )}
        </article>

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

              <p>
                Current assignment summary.
              </p>
            </div>
          </div>

          {reviewerWorkload.length ===
          0 ? (
            <div className="admin-empty-state">
              No active reviewers are
              available.
            </div>
          ) : (
            <div className="admin-reviewer-list">
              {reviewerWorkload.map(
                (reviewer) => (
                  <div
                    className="admin-reviewer-item"
                    key={
                      reviewer.id
                    }
                  >
                    <div className="admin-reviewer-avatar">
                      {reviewer
                        .full_name
                        ?.charAt(0)
                        ?.toUpperCase()}
                    </div>

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

                      <span>
                        {
                          reviewer
                            .currently_reviewing
                        }{" "}
                        currently under review
                      </span>
                    </div>

                    <strong className="admin-reviewer-total">
                      {
                        reviewer
                          .total_assigned
                      }
                    </strong>
                  </div>
                )
              )}
            </div>
          )}
        </article>
      </section>
    </div>
  );
};

export default AdminDashboard;