"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Trash2, XCircle } from "lucide-react";
import toast from "react-hot-toast";

export default function AdminEnrollmentActions({ enrollmentId, status }: { enrollmentId: string; status: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    if (!confirm("Permanently delete this enrollment record?")) return;
    setLoading(true);
    const res = await fetch(`/api/admin/enrollments/${enrollmentId}`, { method: "DELETE" });
    if (res.ok) {
      toast.success("Enrollment deleted.");
      router.refresh();
    } else {
      toast.error("Failed to delete.");
    }
    setLoading(false);
  };

  const handleCancel = async () => {
    if (!confirm("Cancel this enrollment?")) return;
    setLoading(true);
    const res = await fetch(`/api/admin/enrollments/${enrollmentId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "CANCELLED" }),
    });
    if (res.ok) {
      toast.success("Enrollment cancelled.");
      router.refresh();
    } else {
      toast.error("Failed to cancel.");
    }
    setLoading(false);
  };

  return (
    <div className="flex items-center gap-1">
      {status !== "CANCELLED" && (
        <button
          onClick={handleCancel}
          disabled={loading}
          title="Cancel enrollment"
          className="p-1.5 text-amber-500 hover:bg-amber-50 rounded-lg transition-colors disabled:opacity-50"
        >
          <XCircle className="h-4 w-4" />
        </button>
      )}
      <button
        onClick={handleDelete}
        disabled={loading}
        title="Delete record"
        className="p-1.5 text-red-400 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
      >
        <Trash2 className="h-4 w-4" />
      </button>
    </div>
  );
}
