import { useState } from "react";

import type { Workout } from "../../types";
import { Metric } from "../../shared/Metric";

function minutesBetween(start: string, end = new Date().toISOString()) {
  return Math.max(0, Math.round((new Date(end).getTime() - new Date(start).getTime()) / 60000));
}

export function FinishWorkoutDialog({
  workout,
  open,
  pending,
  onClose,
  onFinish,
}: {
  workout: Workout;
  open: boolean;
  pending?: boolean;
  onClose: () => void;
  onFinish: (notes?: string) => void;
}) {
  const [notes, setNotes] = useState(workout.notes ?? "");

  if (!open) return null;

  return (
    <div className="dialog-backdrop" onClick={onClose}>
      <div className="modal-card finish-dialog card" onClick={(event) => event.stopPropagation()}>
        <p className="eyebrow">Workout summary</p>
        <h2>Итог тренировки</h2>
        <div className="modal-stats">
          <Metric label="Длительность" value={`${minutesBetween(workout.started_at)} мин`} />
          <Metric label="Упражнения" value={workout.items.length} />
          <Metric label="Подходы" value={workout.total_sets} />
          <Metric label="Объем" value={`${Math.round(workout.total_volume)} кг`} />
          <Metric label="Калории" value={`~${Math.round(workout.estimated_calories)}`} />
        </div>
        <label>
          Заметка
          <textarea value={notes} onChange={(event) => setNotes(event.target.value)} placeholder="Сегодня хорошо пошёл жим..." />
        </label>
        <div className="modal-actions">
          <button className="ghost" onClick={onClose}>Продолжить</button>
          <button className="primary" disabled={pending} onClick={() => onFinish(notes || undefined)}>
            {pending ? "Сохранение..." : "Сохранить"}
          </button>
        </div>
      </div>
    </div>
  );
}
