import { useQuery } from "@tanstack/react-query";

import { api } from "../../api";
import { useAuth } from "../auth/AuthContext";
import { WorkoutSummary } from "./WorkoutSummary";

export function HistoryPage() {
  const { auth } = useAuth();
  const workouts = useQuery({ queryKey: ["workouts"], queryFn: () => api.workouts(auth.accessToken) });
  const visible = workouts.data?.filter((workout) => workout.status !== "discarded") ?? [];
  const discarded = workouts.data?.filter((workout) => workout.status === "discarded") ?? [];

  return (
    <section className="stack">
      <div className="page-header">
        <div>
          <p className="eyebrow">History</p>
          <h2>История тренировок</h2>
        </div>
      </div>
      {visible.length === 0 && <section className="card empty-state">История пока пустая.</section>}
      {visible.map((workout) => <WorkoutSummary workout={workout} key={workout.id} />)}
      {discarded.length > 0 && (
        <details className="discarded-list card">
          <summary>Отмененные тренировки ({discarded.length})</summary>
          <div className="stack compact-stack">
            {discarded.map((workout) => <WorkoutSummary workout={workout} key={workout.id} />)}
          </div>
        </details>
      )}
    </section>
  );
}
