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

import { api } from "../../api";
import { Metric } from "../../shared/Metric";
import { useAuth } from "../auth/AuthContext";
import { formatSet } from "../workout/setFormat";

export function WorkoutDetailPage() {
  const { workoutId } = useParams({ from: "/workouts/$workoutId" });
  const { auth } = useAuth();
  const workout = useQuery({ queryKey: ["workouts", workoutId], queryFn: () => api.getWorkout(auth.accessToken, workoutId) });

  if (workout.isLoading) return <section className="card loading-card">Загружаю тренировку...</section>;
  if (!workout.data) return <section className="card empty-state">Тренировка не найдена.</section>;

  const data = workout.data;
  return (
    <section className="stack workout-detail">
      <div className="page-header">
        <div>
          <p className="eyebrow">Workout detail</p>
          <h2>{new Date(data.started_at).toLocaleDateString("ru-RU")}</h2>
        </div>
      </div>
      <section className="card detail-hero">
        <Metric label="Статус" value={data.status} />
        <Metric label="Упражнения" value={data.items.length} />
        <Metric label="Подходы" value={data.total_sets} />
        <Metric label="Объем" value={`${Math.round(data.total_volume)} кг`} />
        <Metric label="Ккал" value={`~${Math.round(data.estimated_calories)}`} />
      </section>
      {data.notes && <section className="card notes-card"><h3>Заметки</h3><p>{data.notes}</p></section>}
      {data.items.map((item) => (
        <section className="card detail-item" key={item.id}>
          <h3>{item.title_snapshot}</h3>
          <div className="sets-list">
            {item.sets.map((set) => (
              <div className="set-row" key={set.id}>
                <span className="set-index">{set.set_index}</span>
                <span className="set-data">{formatSet(set, item.measurement_type_snapshot)}</span>
                <span className="set-cal">{set.calories !== null && set.calories !== undefined ? Math.round(set.calories) : "—"} ккал</span>
                <span />
              </div>
            ))}
          </div>
        </section>
      ))}
    </section>
  );
}
