"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import { toast } from "@/lib/toast";

export function GenerateButton({ userId }: { userId: string }) {
  const [loading, setLoading] = useState(false);

  const handleGenerate = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/recommendations/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      });

      if (!res.ok) {
        const error = await res.json();
        toast.error(`Error: ${error.error}`);
      } else {
        toast.success(
          "Recommendation generated successfully! Check Pending Approvals.",
        );
        // In a real app, we'd revalidate the path or update state
        window.location.reload();
      }
    } catch (error) {
      console.error(error);
      toast.error("Failed to generate recommendation.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={handleGenerate}
      disabled={loading}
      className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50 flex items-center"
    >
      {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
      Generate
    </button>
  );
}
