"""
app/utils/excel_export.py
=========================
Genera file Excel per l'inventario con due fogli:

Foglio "Inventario" (prodotti rilevati):
1. Nome Sessione
2. Barcode
3. Nome Prodotto
4. Categoria
5. Giacenza Negozio
6. Giacenza Inventario
7. Differenza (inv-neg)
8. Prezzo Acquisto
9. Prezzo Vendita
10. Valorizzazione Acq. (Giacenza Inventario * Prezzo Acquisto)
11. Valorizzazione Vend. (Giacenza Inventario * Prezzo Vendita)

Foglio "Prodotti non presenti" (non rilevati):
1. Barcode
2. Nome Prodotto
3. Categoria
4. Giacenza Negozio
5. Prezzo Acquisto
6. Prezzo Vendita
"""

from datetime import datetime
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from io import BytesIO


def generate_inventory_excel(
    sede_nome,
    data_valorizzazione,
    products_data,
    tenant_id=1
):
    """
    Genera file Excel per l'inventario.
    """

    workbook = Workbook()

    # Stili condivisi
    style_header = Font(bold=True, size=14, color="FFFFFF")
    fill_header = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid")

    style_colonna = Font(bold=True, size=11, color="FFFFFF")
    fill_colonna = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")

    style_totale = Font(bold=True, size=11)
    fill_totale = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")

    border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )

    # Separa rilevati / non rilevati
    rilevati = [p for p in products_data if p.get('rilevato')]
    non_rilevati = [p for p in products_data if not p.get('rilevato')]

    # ========================================================================
    # FOGLIO 1: INVENTARIO (prodotti rilevati)
    # ========================================================================

    ws_inv = workbook.active
    ws_inv.title = "Inventario"

    # Larghezze colonne (11 colonne, senza Rilevato)
    ws_inv.column_dimensions['A'].width = 20
    ws_inv.column_dimensions['B'].width = 15
    ws_inv.column_dimensions['C'].width = 40
    ws_inv.column_dimensions['D'].width = 20
    ws_inv.column_dimensions['E'].width = 18
    ws_inv.column_dimensions['F'].width = 18
    ws_inv.column_dimensions['G'].width = 18
    ws_inv.column_dimensions['H'].width = 15
    ws_inv.column_dimensions['I'].width = 15
    ws_inv.column_dimensions['J'].width = 18
    ws_inv.column_dimensions['K'].width = 18

    # Intestazione
    row = 1

    cell = ws_inv.cell(row=row, column=1)
    cell.value = f"INVENTARIO {sede_nome.upper()}"
    cell.font = style_header
    cell.fill = fill_header
    cell.alignment = Alignment(horizontal='left', vertical='center')
    ws_inv.merge_cells(f'A{row}:K{row}')
    row += 1

    ws_inv.cell(row=row, column=1).value = f"Data valorizzazione: {data_valorizzazione}"
    ws_inv.cell(row=row, column=1).font = Font(italic=True, size=10)
    row += 2

    # Intestazione colonne
    headers_inv = [
        'Nome Sessione',
        'Barcode',
        'Nome Prodotto',
        'Categoria',
        'Giacenza Negozio',
        'Giacenza Inventario',
        'Differenza (inv-neg)',
        'Prezzo Acquisto',
        'Prezzo Vendita',
        'Valorizzazione Acq.',
        'Valorizzazione Vend.',
    ]

    for col, header in enumerate(headers_inv, 1):
        cell = ws_inv.cell(row=row, column=col)
        cell.value = header
        cell.font = style_colonna
        cell.fill = fill_colonna
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.border = border

    row += 1
    row_data_start = row

    # Dati prodotti rilevati
    for product in rilevati:
        qtà_sistema = float(product.get('quantita_sistema') or 0)
        qtà_fisica = float(product.get('quantita_fisica') or 0)
        costo = float(product.get('costo') or 0)
        prezzo = float(product.get('prezzo_pubblico') or 0)

        ws_inv.cell(row=row, column=1).value = product.get('nome_sessione', '')
        ws_inv.cell(row=row, column=2).value = product.get('barcode', '')
        ws_inv.cell(row=row, column=3).value = product.get('nome_prodotto', '')
        ws_inv.cell(row=row, column=4).value = product.get('categoria', '')
        ws_inv.cell(row=row, column=5).value = qtà_sistema
        ws_inv.cell(row=row, column=6).value = qtà_fisica

        # Colonna G: Differenza = Giacenza Inventario - Giacenza Negozio
        ws_inv.cell(row=row, column=7).value = f'=F{row}-E{row}'

        ws_inv.cell(row=row, column=8).value = costo
        ws_inv.cell(row=row, column=9).value = prezzo

        # Colonna J: Valore Acquisto = Giacenza Inventario * Prezzo Acquisto
        ws_inv.cell(row=row, column=10).value = f'=F{row}*H{row}'

        # Colonna K: Valore Vendita = Giacenza Inventario * Prezzo Vendita
        ws_inv.cell(row=row, column=11).value = f'=F{row}*I{row}'

        # Formattazione
        for col in range(1, 12):
            cell = ws_inv.cell(row=row, column=col)
            cell.border = border
            cell.alignment = Alignment(horizontal='right' if col >= 5 else 'left', wrap_text=False)

            if col in [5, 6, 7]:
                cell.number_format = '0'
            elif col in [8, 9, 10, 11]:
                cell.number_format = '€ #,##0.00'

        row += 1

    # Riga totali
    row_totale = row

    cells_totale = [
        (1, 'TOTALI'),
        (2, ''),
        (3, ''),
        (4, ''),
        (5, f'=SUM(E{row_data_start}:E{row-1})'),
        (6, f'=SUM(F{row_data_start}:F{row-1})'),
        (7, f'=SUM(G{row_data_start}:G{row-1})'),
        (8, ''),
        (9, ''),
        (10, f'=SUM(J{row_data_start}:J{row-1})'),
        (11, f'=SUM(K{row_data_start}:K{row-1})'),
    ]

    for col, value in cells_totale:
        cell = ws_inv.cell(row=row_totale, column=col)
        cell.value = value
        cell.font = style_totale
        cell.fill = fill_totale
        cell.border = border
        cell.alignment = Alignment(horizontal='right' if col >= 5 else 'left')

        if col in [5, 6, 7]:
            cell.number_format = '0'
        elif col in [10, 11]:
            cell.number_format = '€ #,##0.00'

    # Statistiche
    row += 3

    stats = [
        ('Numero prodotti totali', len(products_data)),
        ('Prodotti rilevati', len(rilevati)),
        ('Prodotti non presenti', len(non_rilevati)),
    ]

    for label, value in stats:
        cell1 = ws_inv.cell(row=row, column=1)
        cell1.value = label
        cell1.font = Font(bold=True)

        cell2 = ws_inv.cell(row=row, column=2)
        cell2.value = value

        row += 1

    # ========================================================================
    # FOGLIO 2: PRODOTTI NON PRESENTI (non rilevati)
    # ========================================================================

    ws_np = workbook.create_sheet(title="Prodotti non presenti")

    # Larghezze colonne (6 colonne)
    ws_np.column_dimensions['A'].width = 15
    ws_np.column_dimensions['B'].width = 40
    ws_np.column_dimensions['C'].width = 20
    ws_np.column_dimensions['D'].width = 18
    ws_np.column_dimensions['E'].width = 15
    ws_np.column_dimensions['F'].width = 15

    # Intestazione
    row = 1

    cell = ws_np.cell(row=row, column=1)
    cell.value = f"PRODOTTI NON PRESENTI - {sede_nome.upper()}"
    cell.font = style_header
    cell.fill = fill_header
    cell.alignment = Alignment(horizontal='left', vertical='center')
    ws_np.merge_cells(f'A{row}:F{row}')
    row += 1

    ws_np.cell(row=row, column=1).value = f"Data valorizzazione: {data_valorizzazione}"
    ws_np.cell(row=row, column=1).font = Font(italic=True, size=10)
    row += 2

    # Intestazione colonne
    headers_np = [
        'Barcode',
        'Nome Prodotto',
        'Categoria',
        'Giacenza Negozio',
        'Prezzo Acquisto',
        'Prezzo Vendita',
    ]

    for col, header in enumerate(headers_np, 1):
        cell = ws_np.cell(row=row, column=col)
        cell.value = header
        cell.font = style_colonna
        cell.fill = fill_colonna
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.border = border

    row += 1

    # Dati prodotti non rilevati
    for product in non_rilevati:
        qtà_sistema = float(product.get('quantita_sistema') or 0)
        costo = float(product.get('costo') or 0)
        prezzo = float(product.get('prezzo_pubblico') or 0)

        ws_np.cell(row=row, column=1).value = product.get('barcode', '')
        ws_np.cell(row=row, column=2).value = product.get('nome_prodotto', '')
        ws_np.cell(row=row, column=3).value = product.get('categoria', '')
        ws_np.cell(row=row, column=4).value = qtà_sistema
        ws_np.cell(row=row, column=5).value = costo
        ws_np.cell(row=row, column=6).value = prezzo

        # Formattazione
        for col in range(1, 7):
            cell = ws_np.cell(row=row, column=col)
            cell.border = border
            cell.alignment = Alignment(horizontal='right' if col >= 4 else 'left', wrap_text=False)

            if col == 4:
                cell.number_format = '0'
            elif col in [5, 6]:
                cell.number_format = '€ #,##0.00'

        row += 1

    # ========================================================================
    # EXPORT
    # ========================================================================

    excel_file = BytesIO()
    workbook.save(excel_file)
    excel_file.seek(0)

    return excel_file
