import React, { useMemo } from "react";
import { remainingSwiSummary } from "../../utils/userSwiDashboard.js";

/**
 * @param {{
 *   assignments?: object[],
 *   onViewRemaining?: () => void,
 * }} props
 */
export default function RemainingSwisPanel({
  assignments = [],
  onViewRemaining,
}) {
  const summary = useMemo(
    () => remainingSwiSummary(assignments),
    [assignments],
  );

  const { total, completed, remaining, progress } = summary;
  const clickable = Boolean(onViewRemaining);

  const content = (
    <>
      <div className="swi-user-remaining-progress__head">
        <div className="swi-user-remaining-progress__copy">
          <h2 className="swi-user-remaining-progress__title">Completion</h2>
          <p className="swi-user-remaining-progress__subtitle">
            {total > 0
              ? `${completed} of ${total} SWIs finished`
              : "No SWIs assigned yet"}
          </p>
        </div>
        <div
          className="swi-user-remaining-progress__badge"
          aria-hidden={!total}
        >
          <strong>{progress}</strong>
          <span>%</span>
        </div>
      </div>

      <div
        className="swi-user-remaining-progress__track"
        role="progressbar"
        aria-valuenow={progress}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-label={`SWI completion ${progress} percent`}
      >
        <span
          className="swi-user-remaining-progress__fill"
          style={{ width: `${progress}%` }}
        />
        <span
          className="swi-user-remaining-progress__marker"
          style={{ left: `${progress}%` }}
          aria-hidden
        />
      </div>

      <div className="swi-user-remaining-progress__stats">
        <span className="swi-user-remaining-progress__stat swi-user-remaining-progress__stat--completed">
          <strong>{completed}</strong>
          <span>Completed</span>
        </span>
        <span className="swi-user-remaining-progress__stat swi-user-remaining-progress__stat--remaining">
          <strong>{remaining}</strong>
          <span>Remaining</span>
        </span>
        <span className="swi-user-remaining-progress__stat">
          <strong>{total}</strong>
          <span>Total</span>
        </span>
      </div>
    </>
  );

  if (clickable) {
    return (
      <button
        type="button"
        className="swi-user-remaining-progress swi-panel swi-user-remaining-progress--clickable"
        onClick={onViewRemaining}
        aria-label={`SWI completion ${progress} percent. View remaining assignments.`}
      >
        {content}
      </button>
    );
  }

  return (
    <section className="swi-user-remaining-progress swi-panel" aria-label="SWI completion">
      {content}
    </section>
  );
}
