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

import { api } from "../../api";
import { Metric } from "../../shared/Metric";
import { useAuth } from "../auth/AuthContext";
import { useCatalog } from "../catalog/hooks";

export function AnalyticsPage() {
  const { auth } = useAuth();
  const token = auth.accessToken;
  const { exercises } = useCatalog(token);
  const [exerciseId, setExerciseId] = useState("");
  const progression = useQuery({
    queryKey: ["progression", exerciseId],
    queryFn: () => api.progression(token, "exercise", exerciseId || undefined),
  });
  const calories = useQuery({ queryKey: ["calories"], queryFn: () => api.calories(token) });

  const maxVolume = Math.max(...(progression.data?.points.map((point) => point.volume) ?? [1]), 1);

  return (
    <section className="stack">
      <div className="page-header">
        <div>
          <p className="eyebrow">Analytics</p>
          <h2>Прогрессия и калораж</h2>
        </div>
      </div>
      <section className="card analytics-controls">
        <label>
          Упражнение
          <select value={exerciseId} onChange={(event) => setExerciseId(event.target.value)}>
            <option value="">Все упражнения</option>
            {exercises.data?.map((exercise) => <option key={exercise.id} value={exercise.id}>{exercise.title}</option>)}
          </select>
        </label>
        <Metric label="Последний вес" value={progression.data?.last_weight ?? "нет"} />
        <Metric label="Максимальный вес" value={progression.data?.max_weight ?? "нет"} />
        <Metric label="Калорий всего" value={Math.round(calories.data?.total_calories ?? 0)} />
      </section>
      <section className="card chart-card">
        <h3>Объем по датам</h3>
        <div className="bars">
          {progression.data?.points.map((point) => (
            <div className="bar-row" key={point.date}>
              <span>{point.date}</span>
              <div><i style={{ width: `${Math.max(4, (point.volume / maxVolume) * 100)}%` }} /></div>
              <b>{Math.round(point.volume)}</b>
            </div>
          ))}
        </div>
      </section>
    </section>
  );
}
