'use client';

import { useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Trash2 } from 'lucide-react';

export default function ProgramActions({ programId }: { programId: string }) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const handleDelete = () => {
    if (
      !confirm(
        'Delete this program? Workouts you logged against it stay; only the plan goes away.',
      )
    ) {
      return;
    }
    startTransition(async () => {
      const res = await fetch(`/api/programs/${programId}`, {
        method: 'DELETE',
      });
      if (res.ok) {
        router.push('/main/programs');
        router.refresh();
      } else {
        const body = await res.json().catch(() => ({}));
        alert(body.error ?? `HTTP ${res.status}`);
      }
    });
  };

  return (
    <button
      type="button"
      onClick={handleDelete}
      disabled={pending}
      className="text-xs px-3 py-1.5 rounded border border-red-900 text-red-400 hover:bg-red-900/30 disabled:opacity-50"
    >
      <Trash2 className="inline w-3.5 h-3.5 mr-1" />
      Delete
    </button>
  );
}
