import { useState } from 'react';
import { gameService } from '@/services/game.service';
import { PlayGameResponse, Ticket, PaginatedResponse } from '@/types';
import toast from 'react-hot-toast';

export const useGame = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isLoadingTickets, setIsLoadingTickets] = useState(false);

  const play = async (ticketCode: string): Promise<PlayGameResponse | null> => {
    setIsPlaying(true);
    try {
      const result = await gameService.play(ticketCode);
      toast.success(result.message || 'Vous avez gagné !');
      return result;
    } catch (error: any) {
      console.error('🎲 [useGame] Erreur lors du jeu:', error);
      const errorMessage = error.message || error.data?.message || 'Erreur lors de la participation';
      toast.error(errorMessage);
      return null;
    } finally {
      setIsPlaying(false);
    }
  };

  const getMyTickets = async (
    page = 1,
    limit = 10
  ): Promise<PaginatedResponse<Ticket> | null> => {
    setIsLoadingTickets(true);
    try {
      const tickets = await gameService.getMyTickets(page, limit);
      return tickets;
    } catch (error: any) {
      toast.error(error.message || 'Erreur lors du chargement des tickets');
      return null;
    } finally {
      setIsLoadingTickets(false);
    }
  };

  const getTicketDetails = async (ticketId: string): Promise<Ticket | null> => {
    try {
      const ticket = await gameService.getTicketDetails(ticketId);
      return ticket;
    } catch (error: any) {
      toast.error(error.message || 'Erreur lors du chargement du ticket');
      return null;
    }
  };

  return {
    play,
    getMyTickets,
    getTicketDetails,
    isPlaying,
    isLoadingTickets,
  };
};
