"use client";

import { useActionState } from "react";
import { RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { IDLE_ACTION } from "@/lib/action-state";
import { syncMyCertificatesAction } from "@/actions/certificates";

/**
 * Backfill certificates for every course the student has already finished.
 *
 * Issuing is automatic on the final lesson, but a student who completed a
 * course before the feature existed would otherwise hold nothing and have no
 * way to ask. This gives them one button instead of a support ticket.
 */
export function CertificateSyncButton() {
  const [state, formAction, pending] = useActionState(syncMyCertificatesAction, IDLE_ACTION);

  return (
    <div className="flex flex-wrap items-center gap-3">
      <form action={formAction}>
        <Button type="submit" variant="secondary" loading={pending}>
          <RefreshCw className="size-4" />
          Periksa kelulusan
        </Button>
      </form>

      {state.status === "success" && state.message ? (
        <p className="text-xs text-success-600 dark:text-success-500">{state.message}</p>
      ) : null}
      {state.status === "error" && state.message ? (
        <p className="text-xs text-danger-600 dark:text-danger-500">{state.message}</p>
      ) : null}
    </div>
  );
}
