import discord
from discord import app_commands
import aiohttp
import asyncio
from datetime import datetime, timezone

user_cash = {}
user_bets = {}

def load_database():
    global user_cash
    try:
        with open("database.txt", "r") as f:
            for line in f:
                parts = line.strip().split()
                if len(parts) == 2 and parts[1].startswith("cash(") and parts[1].endswith(")"):
                    user_id = int(parts[0])
                    cash = int(parts[1][5:-1])
                    user_cash[user_id] = cash
    except FileNotFoundError:
        print("No database found. Creating a new one.")

load_database()

async def fetch_nhl_scores():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
            return await response.json()

class GameSelect(discord.ui.Select):
    def __init__(self, games):
        options = [
            discord.SelectOption(
                label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
                value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
                description=f"Start time: {game['startTime']}"
            ) for game in games
        ]
        super().__init__(placeholder="Select a game", options=options)

class TeamSelect(discord.ui.Select):
    def __init__(self, away_team, home_team):
        options = [
            discord.SelectOption(label=away_team['teamName'], value=away_team['abbreviation']),
            discord.SelectOption(label=home_team['teamName'], value=home_team['abbreviation'])
        ]
        super().__init__(placeholder="Select a team to bet on", options=options)

class BetModal(discord.ui.Modal, title="Place Your Bet"):
    bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount")

    def __init__(self, team, user_id, game_data):
        super().__init__()
        self.team = team
        self.user_id = user_id
        self.game_data = game_data

    async def on_submit(self, interaction: discord.Interaction):
        try:
            bet_amount = int(self.bet_amount.value)
            if bet_amount <= 0:
                raise ValueError("Bet more than 0 dollars")
            if bet_amount > user_cash.get(self.user_id, 0):
                raise ValueError("poor")

            user_cash[self.user_id] -= bet_amount
            await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
            
            user = await interaction.client.fetch_user(self.user_id)
            embed = discord.Embed(title="Bet Placed", color=0x787878)
            embed.add_field(name="Team", value=self.team, inline=False)
            embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
            embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
            embed.add_field(name="Start Time", value=self.game_data['startTime'], inline=False)
            await user.send(embed=embed)

            if self.user_id not in user_bets:
                user_bets[self.user_id] = []
            user_bets[self.user_id].append({
                "team": self.team,
                "amount": bet_amount,
                "game_data": self.game_data
            })
            
            asyncio.create_task(self.monitor_game(interaction, bet_amount))
        except ValueError as e:
            await interaction.response.send_message(str(e), ephemeral=True)

    async def monitor_game(self, interaction, bet_amount):
        game_start = datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))
        await asyncio.sleep((game_start - datetime.now(timezone.utc)).total_seconds())

        while True:
            scores = await fetch_nhl_scores()
            game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == self.game_data['teams']['away']['abbreviation'] and 
                         g['teams']['home']['abbreviation'] == self.game_data['teams']['home']['abbreviation']), None)
            
            if game['status']['state'] == 'FINAL':
                winner = 'away' if game['scores']['away'] > game['scores']['home'] else 'home'
                if game['teams'][winner]['abbreviation'] == self.team:
                    winnings = bet_amount * 2
                    user_cash[self.user_id] += winnings
                    await interaction.user.send(f"WOO YOUR TEAM WON you won ${winnings}!")
                else:
                    await interaction.user.send(f"Sorry, your team lost booo!")
                
                user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
                break
            
            await asyncio.sleep(300)

@app_commands.command(name="sportbet", description="bet on sports game")
async def sportbet(interaction: discord.Interaction):
    scores = await fetch_nhl_scores()
    upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']

    if not upcoming_games:
        await interaction.response.send_message("No games for betting.")
        return

    view = discord.ui.View()
    game_select = GameSelect(upcoming_games)
    view.add_item(game_select)

    await interaction.response.send_message("game to bet on:", view=view)

    async def game_callback(interaction: discord.Interaction):
        selected_game = next(game for game in upcoming_games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == game_select.values[0])
        
        team_view = discord.ui.View()
        team_select = TeamSelect(selected_game['teams']['away'], selected_game['teams']['home'])
        team_view.add_item(team_select)

        await interaction.response.edit_message(content="team to bet on:", view=team_view)

        async def team_callback(interaction: discord.Interaction):
            selected_team = team_select.values[0]
            await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, selected_game))

        team_select.callback = team_callback

    game_select.callback = game_callback

@app_commands.command(name="currentbets", description="view your bets")
async def currentbets(interaction: discord.Interaction):
    user_id = interaction.user.id
    if user_id not in user_bets or not user_bets[user_id]:
        await interaction.response.send_message("You have no bets.")
        return

    embed = discord.Embed(title="Your Current Bets", color=0x787878)
    for i, bet in enumerate(user_bets[user_id]):
        scores = await fetch_nhl_scores()
        game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == bet['game_data']['teams']['away']['abbreviation'] and 
                     g['teams']['home']['abbreviation'] == bet['game_data']['teams']['home']['abbreviation']), None)
        
        embed.add_field(name=f"Bet {i+1}", value=f"Team: {bet['team']}\nAmount: ${bet['amount']}\nGame: {bet['game_data']['teams']['away']['teamName']} vs {bet['game_data']['teams']['home']['teamName']}\nCurrent Score: {game['scores']['away']} - {game['scores']['home']}", inline=False)

    view = discord.ui.View()
    cancel_select = discord.ui.Select(placeholder="Select a bet to cancel", options=[
        discord.SelectOption(label=f"Bet {i+1}", value=str(i)) for i in range(len(user_bets[user_id]))
    ])
    view.add_item(cancel_select)

    async def cancel_callback(interaction: discord.Interaction):
        bet_index = int(cancel_select.values[0])
        cancelled_bet = user_bets[user_id].pop(bet_index)
        user_cash[user_id] += cancelled_bet['amount']
        await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")

    cancel_select.callback = cancel_callback

    await interaction.response.send_message(embed=embed, view=view)