"use client";

import { useActionState } from "react";
import { Play, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { startQuizAttemptAction } from "@/actions/quizzes";
import { IDLE_ACTION } from "@/lib/action-state";

/**
 * Opens an attempt and lands on the paper.
 *
 * No client-side navigation here on purpose: the action redirects from the
 * server. It also revalidates the lobby, which remounts this component and
 * resets `useActionState` to idle — so an effect watching for success would
 * never see it.
 *
 * The action returns an existing open attempt rather than creating a second
 * one, so pressing this twice costs nothing and does not burn a try.
 */
export function StartAttemptButton({
  assignmentId,
  resuming,
}: {
  assignmentId: string;
  resuming: boolean;
}) {
  const [state, formAction, pending] = useActionState(startQuizAttemptAction, IDLE_ACTION);

  return (
    <form action={formAction} className="space-y-3">
      <input type="hidden" name="assignmentId" value={assignmentId} />

      {state.status === "error" ? (
        <p className="text-sm text-danger-500">{state.message}</p>
      ) : null}

      <Button type="submit" disabled={pending} className="w-full">
        {resuming ? <RotateCcw className="size-4" /> : <Play className="size-4" />}
        {pending ? "Menyiapkan…" : resuming ? "Lanjutkan percobaan" : "Mulai kerjakan"}
      </Button>
    </form>
  );
}
