"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";

type Props = {
  deliverableId: string;
  token: string;
  approvedAt: string | null; // ISO timestamp or null
};

export function ApproveButton({ deliverableId, token, approvedAt }: Props) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Already approved — show immutable confirmation, no button
  if (approvedAt !== null) {
    const date = new Date(approvedAt).toLocaleDateString("it-IT", {
      day: "2-digit",
      month: "long",
      year: "numeric",
    });
    return (
      <span className="text-xs text-green-700 bg-green-50 border border-green-200 px-2 py-1 rounded">
        Approvato il {date}
      </span>
    );
  }

  async function handleApprove() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/client/approve", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, deliverableId }),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error ?? "Errore durante l'approvazione");
        return;
      }
      router.refresh(); // Re-fetch Server Component data — approved_at now set
    } catch {
      setError("Errore di rete");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <Button
        size="sm"
        variant="outline"
        onClick={handleApprove}
        disabled={loading}
        className="text-xs text-green-700 border-green-300 hover:bg-green-50"
      >
        {loading ? "Approvazione..." : "Approva"}
      </Button>
      {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
    </div>
  );
}