from fastapi import APIRouter, Depends, Response
from sqlalchemy.orm import Session
from io import BytesIO
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
from app.api.module_6_report.schema import Module6ReportPreview
from app.api.module_6_report.service import Module6ReportService
from reportlab.lib.styles import ParagraphStyle
from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student

module_6_report_router = APIRouter()


@module_6_report_router.get("/{group_id}/preview6", response_model=Module6ReportPreview)
async def preview_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    service = Module6ReportService(db, token)
    return await service._fetch_module6_data(group_id)


@module_6_report_router.get("/{group_id}/download6")
async def download_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    service = Module6ReportService(db, token)
    report = await service._fetch_module6_data(group_id)

    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=50, rightMargin=50, topMargin=50, bottomMargin=50)
    elements = []
    styles = getSampleStyleSheet()
    
    # Title
    title_style = ParagraphStyle(
        'Title',
        parent=styles['Heading1'],
        fontSize=18,
        spaceAfter=20,
        alignment=1,
        fontName='Helvetica-Bold'
    )
    # Logo
    try:
        logo = Image("TS Logo.png", width=150, height=75)
        logo.hAlign = 'LEFT'
        elements.append(logo)
        elements.append(Spacer(1, 10))
    except:
        pass  # Continue without logo if file not found
    
    elements.append(Paragraph("Module 6: Promotions", title_style))
    elements.append(Spacer(1, 12))

    # Section style
    section_style = ParagraphStyle(
        'SectionHeader',
        parent=styles['Heading2'],
        fontSize=14,
        spaceAfter=10,
        fontName='Helvetica-Bold'
    )

    # Cell style for table content
    cell_style = ParagraphStyle(
        'CellStyle',
        parent=styles['Normal'],
        fontSize=10,
        leading=12,
        wordWrap='CJK'
    )

    # Header cell style
    header_style = ParagraphStyle(
        'HeaderStyle',
        parent=styles['Normal'],
        fontSize=10,
        leading=12,
        fontName='Helvetica-Bold',
        wordWrap='CJK'
    )

    def safe_str(value):
        return str(value) if value not in [None, "", "N/A", 0] else "N/A"

    # Competitor Analysis on Pricing Strategy
    elements.append(Paragraph("Competitor Analysis on Pricing Strategy", section_style))
    elements.append(Spacer(1, 10))
    
    pricing_data = [
        [Paragraph("Reference Competitor", header_style), Paragraph(safe_str(report.competitor_pricing_analysis.reference_competitor), cell_style)],
        [Paragraph("Pricing Strategy", header_style), Paragraph(safe_str(report.competitor_pricing_analysis.pricing_strategy), cell_style)],
        [Paragraph("Highest Income Category", header_style), Paragraph(safe_str(report.competitor_pricing_analysis.which_category_generates_the_most_income_for_the_store), cell_style)],
        [Paragraph("Key Observations", header_style), Paragraph(safe_str(report.competitor_pricing_analysis.key_observation_around_pricing_in_the_store), cell_style)],
        [Paragraph("Other Remarks", header_style), Paragraph(safe_str(report.competitor_pricing_analysis.other_remarks), cell_style)]
    ]
    
    pricing_table = Table(pricing_data, colWidths=[150, 350])
    pricing_table.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('LEFTPADDING', (0, 0), (-1, -1), 8),
        ('RIGHTPADDING', (0, 0), (-1, -1), 8),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8)
    ]))
    elements.append(pricing_table)
    elements.append(Spacer(1, 20))

    # Pricing Strategy by Store Format
    elements.append(Paragraph("Pricing Strategy by Store Format", section_style))
    elements.append(Spacer(1, 10))
    
    # Get Store Format A and B data
    format_a = next((sf for sf in report.store_format_pricing_strategis if "A" in str(sf.store_format_type)), None)
    format_b = next((sf for sf in report.store_format_pricing_strategis if "B" in str(sf.store_format_type)), None)
    
    # If no specific A/B formats, use first two or create defaults
    if not format_a and not format_b:
        format_a = report.store_format_pricing_strategis[0] if len(report.store_format_pricing_strategis) > 0 else None
        format_b = report.store_format_pricing_strategis[1] if len(report.store_format_pricing_strategis) > 1 else None
    
    # Create table with headers and data rows
    store_format_data = [
        # Header row
        [Paragraph("Store Format", header_style), 
         Paragraph("Pricing Strategy", header_style), 
         Paragraph("Rationale", header_style)],
        # Store Format A row
        [Paragraph("Store Format A", cell_style),
         Paragraph(safe_str(format_a.choose_a_pricing_strategies) if format_a else "N/A", cell_style),
         Paragraph(safe_str(format_a.rational) if format_a else "N/A", cell_style)],
        # Store Format B row
        [Paragraph("Store Format B", cell_style),
         Paragraph(safe_str(format_b.choose_a_pricing_strategies) if format_b else "N/A", cell_style),
         Paragraph(safe_str(format_b.rational) if format_b else "N/A", cell_style)]
    ]
    
    store_format_table = Table(store_format_data, colWidths=[120, 140, 240])
    store_format_table.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
        ('LEFTPADDING', (0, 0), (-1, -1), 8),
        ('RIGHTPADDING', (0, 0), (-1, -1), 8),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8)
    ]))
    elements.append(store_format_table)
    elements.append(Spacer(1, 20))

    # Competitor Analysis on Promotions - Start on new page
    elements.append(PageBreak())
    elements.append(Paragraph("Competitor Analysis on Promotions", section_style))
    elements.append(Spacer(1, 10))
    
    promotions_data = [
        [Paragraph("Reference Competitor", header_style), Paragraph(safe_str(report.define_your_promotions_strategy.reference_competitor), cell_style)],
        [Paragraph("Ongoing Key Promotions", header_style), Paragraph(safe_str(report.define_your_promotions_strategy.ongoing_key_promotions), cell_style)],
        [Paragraph("Among the various promotions, which one do you think is the most effective/useful for the competitor", header_style), Paragraph(safe_str(report.define_your_promotions_strategy.amoung_key_variouse_promotion), cell_style)],
        [Paragraph("What are some key observations around promotions in the store?", header_style), Paragraph(safe_str(report.define_your_promotions_strategy.what_are_the_same_key), cell_style)],
        [Paragraph("Other Remarks", header_style), Paragraph(safe_str(report.define_your_promotions_strategy.other_remark), cell_style)]
    ]
    
    promotions_table = Table(promotions_data, colWidths=[250, 250])
    promotions_table.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
        ('LEFTPADDING', (0, 0), (-1, -1), 8),
        ('RIGHTPADDING', (0, 0), (-1, -1), 8),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8)
    ]))
    elements.append(promotions_table)
    elements.append(Spacer(1, 20))

    # Yearly Promotion List
    elements.append(Paragraph("Yearly Promotion List", section_style))
    elements.append(Spacer(1, 10))
    
    # Header row for promotional calendar
    yearly_promotion_headers = [
        [Paragraph("Month", header_style), 
         Paragraph("Category", header_style), 
         Paragraph("Type of Promotion", header_style),
         Paragraph("Success Metric", header_style),
         Paragraph("Objective", header_style),
         Paragraph("Remarks", header_style)]
    ]
    
    # Data rows from promotional calendar
    yearly_promotion_rows = []
    for promo in report.promotional_calendar:
        yearly_promotion_rows.append([
            Paragraph(safe_str(promo.month), cell_style),
            Paragraph(safe_str(promo.category), cell_style),
            Paragraph(safe_str(promo.type_of_promotion), cell_style),
            Paragraph(safe_str(promo.success_metric), cell_style),
            Paragraph(safe_str(promo.objective), cell_style),
            Paragraph(safe_str(promo.remarks), cell_style)
        ])
    
    yearly_promotion_table = Table(yearly_promotion_headers + yearly_promotion_rows, colWidths=[60, 80, 80, 80, 80, 120])
    yearly_promotion_table.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6)
    ]))
    elements.append(yearly_promotion_table)
    elements.append(Spacer(1, 20))

    # Category Pricing Strategies
    if report.category_pricing_strategis:
        elements.append(Paragraph("Category Pricing Strategies", section_style))
        elements.append(Spacer(1, 10))
        
        category_headers = [
            [Paragraph("Category", header_style), Paragraph("Pricing Strategy", header_style), Paragraph("Rationale", header_style)]
        ]
        
        category_rows = []
        for category in report.category_pricing_strategis:
            category_rows.append([
                Paragraph(safe_str(category.category), cell_style),
                Paragraph(safe_str(category.pricing_strategis), cell_style),
                Paragraph(safe_str(category.rational), cell_style)
            ])
        
        category_table = Table(category_headers + category_rows, colWidths=[120, 120, 260])
        category_table.setStyle(TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
            ('LEFTPADDING', (0, 0), (-1, -1), 8),
            ('RIGHTPADDING', (0, 0), (-1, -1), 8),
            ('TOPPADDING', (0, 0), (-1, -1), 8),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 8)
        ]))
        elements.append(category_table)
        elements.append(Spacer(1, 20))

    doc.build(elements)
    buffer.seek(0)
    
    return Response(
        content=buffer.getvalue(),
        media_type="application/pdf",
        headers={"Content-Disposition": f"attachment; filename=module6_pricing_promotions_loyalty_{group_id}.pdf"}
    )


@module_6_report_router.get("/{group_id}/preview-report-pdf6")
async def generate_and_serve_pdf(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Generate PDF report and return file path information"""
    try:
        service = Module6ReportService(db, token)
        file_path = await service.generate_and_save_pdf(group_id)
        
        return {
            "group_id": group_id,
            "file_path": file_path,
        }
            
    except Exception as e:
        from fastapi import HTTPException
        raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")