"use client";
import { useEffect, useState } from "react";
import { fetchClient } from "@/lib/api-client";

interface Invitation {
  _id: string;
  code: string;
  isUsed: boolean;
  createdAt: string;
  expiresAt: string;
  usedAt?: string | null;
}

export default function InvitationsListCard() {
  const [invites, setInvites] = useState<Invitation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const data = await fetchClient<Invitation[]>("/admin/invitations");
        if (mounted) setInvites(data);
      } catch (e: any) {
        if (mounted) setError(e?.message || "Failed to load invitations");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  return (
    <div className="rounded-lg border border-border/60 bg-background p-4 h-full min-h-[200px]">
      <h2 className="font-medium">Invitations</h2>
      <p className="text-sm text-muted-foreground mt-1">Active and recent invitations</p>

      {loading ? (
        <p className="text-sm text-muted-foreground mt-3">Loading...</p>
      ) : error ? (
        <p className="text-sm text-muted-foreground mt-3">{error}</p>
      ) : invites.length === 0 ? (
        <p className="text-sm text-muted-foreground mt-3">No invitations found</p>
      ) : (
        <div className="mt-3 space-y-2">
          {invites.map((inv) => {
            const expired = new Date(inv.expiresAt).getTime() < Date.now();
            return (
              <div key={inv._id} className="rounded border border-border/50 p-3 text-sm flex items-center justify-between">
                <div className="space-y-1">
                  <div>
                    Code: <span className="font-mono px-1.5 py-0.5 rounded bg-muted">{inv.code}</span>
                  </div>
                  <div className="text-xs text-muted-foreground">
                    Created: {new Date(inv.createdAt).toLocaleString()} · Expires: {new Date(inv.expiresAt).toLocaleString()}
                  </div>
                </div>
                <span className={`text-xs px-2 py-0.5 rounded ${inv.isUsed ? 'bg-emerald-500/15 text-emerald-400' : expired ? 'bg-rose-500/15 text-rose-400' : 'bg-amber-500/15 text-amber-400'}`}>
                  {inv.isUsed ? 'Used' : expired ? 'Expired' : 'Active'}
                </span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}


