# -*- coding: utf-8 -*-
"""
Created on Tue Sep  9 10:37:23 2025

@author: adria
"""

from io import BytesIO
import pandas as pd 
from openpyxl.drawing.image import Image
import base64 
import streamlit as st
import logging 
from ..utils import set_logger_config

logger = logging.getLogger(__name__)
set_logger_config()


def download_excel_dfs(
        dataframes, 
        result_name, 
        session_state=False, 
        button_text="Download Excel Results",
        run_type=None,
        ):
    
    output = BytesIO()

    if run_type==None:
        with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
            # Guardar los dataframes
            for sheetname, df in dataframes["Dataframes"].items():
                if not(isinstance(df, list)):
                    df.to_excel(writer, sheet_name=sheetname, index=False)
                    writer.sheets[sheetname].freeze_panes = 'A2'
                else:
                    for i, sub_df in enumerate(df):
                        if i==0:
                            sub_df.to_excel(writer, sheet_name=sheetname, index=False, startrow=0, startcol=0)
                            sub_df_shape = len(sub_df.columns)
                        else:
                            sub_df.to_excel(writer, sheet_name=sheetname, index=False, startrow=0, startcol=sub_df_shape + 2)
                        writer.sheets[sheetname].freeze_panes = 'A2'

            # Insertar imagen si existe
            if "image" in dataframes:
                img_stream = dataframes["image"]
                img = Image(img_stream)
                img.width = 500
                img.height = 300
                img.anchor = 'BG2'
                first_sheetname = next(iter(writer.sheets))
                writer.sheets[first_sheetname].add_image(img)
    else:

        with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
            for sheet_name, df in dataframes["Dataframes"].items():
                if isinstance(df, pd.DataFrame):
                    safe_sheet_name = sheet_name[:31]
                    df.to_excel(writer, sheet_name=safe_sheet_name, index=False)

                    if sheet_name in ['Daily', 'Monthly', 'Annual']:
                        workbook  = writer.book
                        worksheet = writer.sheets[safe_sheet_name]
                        percent_format = workbook.add_format({'num_format': '0.00%'})

                        for col_num, value in enumerate(df.columns):
                            if 'EV' not in value and ('ER' in value or 'TR' in value):
                                worksheet.set_column(col_num, col_num, 12, percent_format)

                elif isinstance(df, list):
                    for i, sub_df in enumerate(df):
                        if i == 0:
                            sub_df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=0, startcol=0)
                            sub_df_shape = len(sub_df.columns)
                        else:
                            sub_df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=0, startcol=sub_df_shape + 2)
                        writer.sheets[sheet_name].freeze_panes = 'A2'

                else:
                    logger.warning('df is neither a dataframe or a list of dataframes')


    output.seek(0)
    
    b64 = base64.b64encode(output.read()).decode('utf-8')
    
    st.markdown("""
        <style>
        .streamlit-button-style {
            background-color: #ffffff;
            color: #444444;
            border: 1px solid rgba(49, 51, 63, 0.2);
            border-radius: 0.5rem;
            padding: 0.375rem 0.75rem;
            font-size: 0.93rem;
            height: 40px;
            font-weight: 500;
            font-family: "Source Sans Pro", sans-serif;
            line-height: 1.5;
            margin-bottom: 15px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        .streamlit-button-style:hover {
            background-color: #E0E2E6;
        }
        .streamlit-button-style:active {
            background-color: #6b6a6a;
            color: #f8f8f8  
            }
        </style>
    """, unsafe_allow_html=True)

    href = f"""
    <a href="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,{b64}" download="{result_name}">
        <button class="streamlit-button-style">
            {button_text}
        </button>
    </a>
    """
    
    
    if session_state:
        return href
    else:
        output.seek(0)
        return output, href