import { useState, useEffect } from 'react';
import { Tooltip, Avatar } from 'antd';
import { HeartOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import UserAvatar from './UserAvatar';

interface FriendInfo {
  id: string;
  name: string | null;
  email: string;
}

interface Props {
  campaignId: string;
}

export default function FriendsCampaignBadge({ campaignId }: Props) {
  const { isAuthenticated } = useAuthStore();
  const { settings } = useSettingsStore();
  const [friends, setFriends] = useState<FriendInfo[]>([]);

  useEffect(() => {
    if (!isAuthenticated || !settings?.enableSocial) return;
    api.get(`/social/integration/campaigns/${campaignId}/friends`)
      .then(({ data }) => setFriends(data.friends || []))
      .catch(() => {});
  }, [campaignId, isAuthenticated, settings?.enableSocial]);

  if (!isAuthenticated || !settings?.enableSocial || friends.length === 0) return null;

  const displayFriends = friends.slice(0, 3);
  const remaining = friends.length - displayFriends.length;

  return (
    <Tooltip
      title={
        friends.length <= 5
          ? friends.map((f) => f.name || f.email).join(', ')
          : `${friends.slice(0, 5).map((f) => f.name || f.email).join(', ')} and ${friends.length - 5} more`
      }
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
        <HeartOutlined style={{ color: '#eb2f96', fontSize: 13 }} />
        <Avatar.Group size="small" max={{ count: 3 }}>
          {displayFriends.map((f) => (
            <UserAvatar key={f.id} userId={f.id} name={f.name || f.email} size={24} />
          ))}
          {remaining > 0 && (
            <Avatar size={24} style={{ backgroundColor: '#eb2f96', fontSize: 11 }}>
              +{remaining}
            </Avatar>
          )}
        </Avatar.Group>
        <span style={{ color: '#eb2f96', fontSize: 12, fontWeight: 500 }}>
          {friends.length} friend{friends.length !== 1 ? 's' : ''} participated
        </span>
      </div>
    </Tooltip>
  );
}
