'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';

export default function StartSessionButton({
  programId,
  dayId,
}: {
  programId: string;
  dayId: string;
}) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  const handleClick = async () => {
    setBusy(true);
    try {
      const res = await fetch(
        `/api/programs/${programId}/days/${dayId}/start`,
        { method: 'POST' },
      );
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        alert(body.error ?? `HTTP ${res.status}`);
        setBusy(false);
        return;
      }
      const workout = await res.json();
      router.push(`/main/workouts/${workout.id}`);
    } catch (e) {
      alert((e as Error).message);
      setBusy(false);
    }
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={busy}
      className="mt-3 inline-block text-xs uppercase tracking-wider px-3 py-1.5 rounded bg-emerald-700 hover:bg-emerald-600 text-white font-bold disabled:opacity-50"
    >
      {busy ? (
        <>
          <Loader2 className="inline w-3.5 h-3.5 animate-spin mr-1" />
          Starting...
        </>
      ) : (
        'Start this session →'
      )}
    </button>
  );
}
