'use client';
import Link from 'next/link';

import { useState, useEffect, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { Button, Badge } from 'react-bootstrap';
import { useAuth } from '@/contexts/AuthContext';
import { getParticipations, registerParticipation, cancelParticipation, Participant } from '@/services/participationService';

interface ParticipationButtonProps {
  evenementId: number;
  eventDate: string;
}

export default function ParticipationButton({ evenementId, eventDate }: ParticipationButtonProps) {
  const t = useTranslations('Participation');
  const { isAuthenticated, user } = useAuth();

  const [participants, setParticipants] = useState<Participant[]>([]);
  const [count, setCount] = useState(0);
  const [myParticipationId, setMyParticipationId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);

  const isPast = new Date(eventDate) < new Date();

  const loadParticipations = useCallback(async () => {
    try {
      const data = await getParticipations(evenementId);
      setCount(data.count);
      setParticipants(data.participants);

      if (isAuthenticated && user?.username) {
        const mine = data.participants.find(p => p.pseudo === user.username);
        setMyParticipationId(mine?.id || null);
      }
    } catch {
      // silently fail
    }
  }, [evenementId, isAuthenticated, user]);

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

  const handleToggle = async () => {
    setLoading(true);
    try {
      if (myParticipationId) {
        await cancelParticipation(myParticipationId);
        setMyParticipationId(null);
        setCount(prev => prev - 1);
      } else {
        const result = await registerParticipation(evenementId);
        setMyParticipationId(result.id);
        setCount(prev => prev + 1);
      }
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  };

  const label = isPast ? t('was_there') : t('will_be_there');

  return (
    <div className="participation-section d-flex align-items-center gap-2">
      {!isAuthenticated && (
        <Link href="/connexion" className="tk-text-muted">
          {t('login_to_participate')}
        </Link>
      )}
      {isAuthenticated && (
        <Button
          variant={myParticipationId ? 'success' : 'outline-success'}
          size="sm"
          onClick={handleToggle}
          disabled={loading}
        >
          {myParticipationId ? label : (isPast ? t('i_was_there') : t('i_will_be_there'))}
        </Button>
      )}
      <Badge bg="secondary">{count} {t('participants')}</Badge>
    </div>
  );
}
