'use client';

import { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/badge';
import { User } from 'lucide-react';

interface ContactCellProps {
  contactId?: number;
}

export function ContactCell({ contactId }: ContactCellProps) {
  const [contactName, setContactName] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!contactId) {
      setContactName(null);
      return;
    }

    const fetchContact = async () => {
      setLoading(true);
      try {
        const response = await fetch(`/api/contacts/${contactId}`);
        if (response.ok) {
          const data = await response.json();
          if (data.contact) {
            setContactName(`${data.contact.firstName} ${data.contact.lastName}`);
          }
        }
      } catch (err) {
        console.error('Failed to fetch contact:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchContact();
  }, [contactId]);

  if (loading) {
    return <span className="text-xs text-muted-foreground">Loading...</span>;
  }

  if (!contactId) {
    return <span className="text-xs text-muted-foreground">-</span>;
  }

  if (contactName) {
    return (
      <Badge variant="outline" className="text-xs">
        <User className="w-3 h-3 mr-1" />
        {contactName}
      </Badge>
    );
  }

  return <span className="text-xs text-muted-foreground">ID: {contactId}</span>;
}
