"use client";

import { useQuery } from "@tanstack/react-query";

type AuditEvent = {
  id: string;
  hubspotDealId: string;
  measureName: string;
  action: string;
  actedByEmail: string;
  actedByName: string | null;
  actedAt: string;
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function ActivityLog({
  dealId,
  portfolioId,
}: {
  dealId: string;
  portfolioId: string;
}) {
  const { data, isLoading } = useQuery<{ events: AuditEvent[] }>({
    queryKey: ["approvalEvents", portfolioId, dealId],
    queryFn: async () => {
      const res = await fetch(
        `/api/portfolio/${portfolioId}/approvals?dealIds=${dealId}&include=events`,
      );
      if (!res.ok) throw new Error("Failed to fetch events");
      return res.json();
    },
    staleTime: 30_000,
  });

  if (isLoading) {
    return (
      <p className="text-xs text-gray-400 py-2 pl-4">Loading activity…</p>
    );
  }

  const events = data?.events ?? [];

  if (events.length === 0) {
    return (
      <p className="text-xs text-gray-400 py-2 pl-4">No activity yet.</p>
    );
  }

  return (
    <div className="relative">
      <div className="max-h-48 overflow-y-auto pl-4 pr-2 pb-3 space-y-1.5">
        {events.map((e) => (
          <div key={e.id} className="flex items-center gap-2 text-xs">
            <span
              className={`px-1.5 py-0.5 rounded text-xs font-medium ${
                e.action === "approved"
                  ? "bg-emerald-50 text-emerald-700"
                  : "bg-red-50 text-red-600"
              }`}
            >
              {e.action === "approved" ? "Approved" : "Unapproved"}
            </span>
            <span className="font-medium text-gray-700">{e.measureName}</span>
            <span className="text-gray-400">·</span>
            <span className="text-gray-500">
              {e.actedByName ?? e.actedByEmail}
            </span>
            <span className="text-gray-400">·</span>
            <span className="text-gray-400">{formatDate(e.actedAt)}</span>
          </div>
        ))}
      </div>
      {events.length > 4 && (
        <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-white to-transparent" />
      )}
    </div>
  );
}
