import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from pyTSPA.metrics import result_stats, team_performance, each_win_percentage, each_pythagorean_expectation, each_team_performance

sns.set_theme(style="whitegrid")

def plot_result_distribution(df: pd.DataFrame):

    """
    Visualizes overall result distribution: home wins, draws, away wins.

    Args: df (pd.DataFrame): dataframe containing match data with 'FTR' column

    Returns: None
    """
    results = result_stats(df)
    result_names = list(results.keys())
    result_counts = list(results.values())

    plt.figure(figsize=(8, 5))
    sns.barplot(x=result_names, y=result_counts, palette="muted")
    plt.title("Match Result Distribution")
    plt.ylabel("Number of Matches")
    plt.xlabel("Result")
    plt.tight_layout()
    plt.show()

def plot_team_results(df: pd.DataFrame, team_name: str):

    """
    Plots wins, draws, and losses for a single team.

    Args: df (pd.DataFrame): dataframe containing match data with 'HomeTeam', 'AwayTeam', 'FTR' columns
          team_name (str): name of the team to visualize results for

    Returns: None
    """
    stats = team_performance(df, team_name)
    results = {
        'Wins': stats['Wins'],
        'Draws': stats['Draws'],
        'Losses': stats['Losses']
    }

    plt.figure(figsize=(8, 5))
    sns.barplot(x=list(results.keys()), y=list(results.values()), palette="deep")
    plt.title(f"{team_name} - Match Outcomes")
    plt.ylabel("Number of Matches")
    plt.xlabel("Result Type")
    plt.tight_layout()
    plt.show()

def plot_league_points_table(df: pd.DataFrame):

    """
    Plots total points for all teams as a horizontal bar chart.

    Args: df (pd.DataFrame): dataframe generated by each_team_performance()

    Returns: None
    """
    sorted_df = df.sort_values(by="Points", ascending=True)
    plt.figure(figsize=(10, 12))
    sns.barplot(x="Points", y="Team", data=sorted_df, palette="viridis")
    plt.title("League Table - Points by Team")
    plt.xlabel("Points")
    plt.ylabel("Team")
    plt.tight_layout()
    plt.show()

def plot_goal_difference_distribution(df: pd.DataFrame):

    """
    Visualizes goal difference distribution for all teams.

    Args: df (pd.DataFrame): dataframe generated by each_team_performance()

    Returns: None
    """
    plt.figure(figsize=(10, 6))
    sns.barplot(x="Goal Difference", y="Team", data=df.sort_values(by="Goal Difference", ascending=True), palette="coolwarm")
    plt.title("Goal Difference Distribution by Team")
    plt.xlabel("Goal Difference")
    plt.ylabel("Team")
    plt.tight_layout()
    plt.show()

def plot_win_percentage_comparison(df: pd.DataFrame):

    """
    Compares win percentage for all teams as a bar chart.

    Args: df (pd.DataFrame): dataframe generated by each_win_percentage()

    Returns: None
    """
    plt.figure(figsize=(12, 8))
    sns.barplot(x="WinPercentage", y="Team", data=df.sort_values(by="WinPercentage", ascending=True), palette="magma")
    plt.title("Win Percentage by Team")
    plt.xlabel("Win Percentage")
    plt.ylabel("Team")
    plt.tight_layout()
    plt.show()


def plot_pythagorean_expectation(df: pd.DataFrame):

    """
    Visualizes pythagorean expectation alongside actual points for each team.

    Args: df (pd.DataFrame): dataframe generated by each_team_performance() with pythagorean expectation values included

    Returns: None
    """
    plt.figure(figsize=(12, 8))
    sns.scatterplot(x="PythagoreanExpectation", y="Points", data=df, hue="Team", palette="tab20", s=100)
    plt.title("Pythagorean Expectation vs. Actual Points")
    plt.xlabel("Pythagorean Expectation")
    plt.ylabel("Points")
    plt.tight_layout()
    plt.show()