'use client';

import { useState, useEffect, useCallback } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import Link from 'next/link';
import { getParticipations, Participant } from '@/services/participationService';

const AVATAR_TONES = ['#6f9fba', '#ee8b00', '#a2b029', '#8b8377', '#5b8fae'];

interface ParticipantSectionProps {
  evenementId: number;
}

export default function ParticipantSection({ evenementId }: ParticipantSectionProps) {
  const t = useTranslations('Participation');
  const locale = useLocale();
  const [participants, setParticipants] = useState<Participant[]>([]);
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(true);

  const loadParticipants = useCallback(async () => {
    try {
      setLoading(true);
      const data = await getParticipations(evenementId);
      setParticipants(data.participants);
      setCount(data.count);
    } catch {
      // Silent fail - participants are not critical
    } finally {
      setLoading(false);
    }
  }, [evenementId]);

  useEffect(() => {
    loadParticipants();
  }, [loadParticipants]);

  if (loading) {
    return <p className="tk-text-muted">...</p>;
  }

  if (count === 0) {
    return (
      <div className="tk-participants mt-4">
        <div className="tk-participants__head">
          <span className="tk-participants__eyebrow">{t('participants_title')}</span>
        </div>
        <p className="tk-text-muted mb-0">{t('empty')}</p>
      </div>
    );
  }

  return (
    <div className="tk-participants mt-4">
      <div className="tk-participants__head">
        <span className="tk-participants__eyebrow">{t('participants_title')}</span>
        <span className="tk-participants__count">
          <b>{count}</b> {t('members_attending')}
        </span>
      </div>
      <div className="tk-participants__list">
        {participants.map((p, index) => (
          <Link key={p.id} href={`/${locale}/profil/${p.userId}`} className="tk-participants__chip">
            <span
              className="tk-participants__avatar"
              style={{ background: AVATAR_TONES[index % AVATAR_TONES.length] }}
              aria-hidden="true"
            >
              {(p.pseudo || '?').charAt(0).toUpperCase()}
            </span>
            {p.pseudo}
          </Link>
        ))}
      </div>
    </div>
  );
}
