import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd


# 1: This function to create bloom plot by highlighting bloom events in a time series of chlorophyll data
def plot_bloom_events(
    df: pd.DataFrame,
    bloom_data: dict,
    region_name: str = "Region",
    time_col: str = 'day_of_year',
    chl_col: str = 'CHL',
    ylabel: str = 'Chl-a (mg m$^{-3}$)'
) -> None:
    """
    Replicates exact bloom visualization style:
    - Whitegrid style
    - Steelblue CHL curve
    - Red dashed threshold line
    - Rainbow-colored bloom regions
    - Legend in upper right outside plot
    
    Args:
        df: Input DataFrame
        bloom_data: Output from detect_bloom_events()
        region_name: Region name for title
        time_col: Time index column
        chl_col: Chlorophyll column
        ylabel: Y-axis label text
    """
    plt.figure(figsize=(14, 7))
    sns.set_style("whitegrid")
    
    # Plot CHL curve
    ax = sns.lineplot(
        data=df, 
        x=time_col, 
        y=chl_col, 
        linewidth=2, 
        color='steelblue', 
        label='CHL Concentration'
    )
    
    # Add threshold line
    plt.axhline(
        y=bloom_data['threshold'], 
        color='red', 
        linestyle='--', 
        linewidth=1.5, 
        label=f'Threshold: {bloom_data["threshold"]:.3f}'
    )
    
    # Plot each bloom event with rainbow colors
    n_blooms = len(bloom_data['bloom_events'])
    colors = plt.cm.rainbow(np.linspace(0, 1, n_blooms)) if n_blooms > 0 else []
    
    for i, (bloom, color) in enumerate(zip(bloom_data['bloom_events'], colors), 1):
        plt.axvspan(
            bloom['start_day'], 
            bloom['end_day'], 
            color=color, 
            alpha=0.2, 
            label=f'Bloom {i}'
        )
    
    # Configure title and labels
    plt.title(
        f'All Phytoplankton Bloom Events\n{region_name.title()} Sea', 
        fontsize=16, 
        pad=20
    )
    plt.xlabel(
        time_col.replace('_', ' ').title(), 
        fontsize=14
    )
    plt.ylabel(
        ylabel, 
        fontsize=14
    )
    
    # Position legend outside plot
    plt.legend(
        loc='upper right', 
        bbox_to_anchor=(1.15, 1), 
        borderaxespad=0.
    )
    
    plt.tight_layout()
    plt.show()