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, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
from app.api.module_7_report.schema import Module7ReportPreview
from app.api.module_7_report.service import Module7ReportService
from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student

module_7_report_router = APIRouter()


@module_7_report_router.get("/{group_id}/preview7", response_model=Module7ReportPreview)
async def preview_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    service = Module7ReportService(db, token)
    return await service._fetch_module7_data(group_id)


@module_7_report_router.get("/{group_id}/download7")
async def download_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    service = Module7ReportService(db, token)
    report = await service._fetch_module7_data(group_id)

    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=40, rightMargin=40, topMargin=40, bottomMargin=40)
    elements = []
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        alignment=1  # Center alignment
    )
    section_style = styles['Heading2']
    normal = styles['Normal']

    # Currency formatting function
    def format_currency(amount):
        """Format currency with Rs. prefix"""
        if amount is None or amount == 0:
            return "Rs. 0"
        return f"Rs. {amount:,.0f}"

    # 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

    # Module Title
    elements.append(Paragraph("Module 7: Marketing Communications", title_style))
    elements.append(Spacer(1, 12))

    # Brand Attribute Assessment
    elements.append(Paragraph("<b>Brand Attribute Assessment</b>", section_style))
    elements.append(Paragraph(f"Research Methodology: {report.brand_attribute_assessment.define_research_methodology}", normal))
    elements.append(Paragraph(f"Top 10 Attributes: {report.brand_attribute_assessment.name_top_10_attributes}", normal))
    elements.append(Paragraph(f"Remarks: {report.brand_attribute_assessment.remarks}", normal))
    elements.append(Spacer(1, 12))

    # Branding & USP
    elements.append(Paragraph("<b>Branding & USP</b>", section_style))
    
    # Brand Attributes Comparison Table with flexible wrapping
    cell_style = ParagraphStyle("CellStyle", fontSize=9, leading=11, wordWrap="CJK")
    brand_data = [[
        Paragraph("<b>Attributes</b>", cell_style), 
        Paragraph("<b>Reference Retailer 1</b>", cell_style), 
        Paragraph("<b>Reference Retailer 2</b>", cell_style), 
        Paragraph("<b>Own Brand</b>", cell_style)
    ]]
    brand_data.append([
        Paragraph(str(report.branding_attributes.attributes or "N/A"), cell_style),
        Paragraph(str(report.branding_attributes.reference_retailer_1 or "N/A"), cell_style),
        Paragraph(str(report.branding_attributes.reference_retailer_2 or "N/A"), cell_style),
        Paragraph(str(report.branding_attributes.own_brand or "N/A"), cell_style)
    ])
    
    brand_table = Table(brand_data)
    brand_table.setStyle(TableStyle([
        ("GRID", (0, 0), (-1, -1), 1, colors.black),
        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
        ("ALIGN", (0, 0), (-1, -1), "LEFT"),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
    ]))
    elements.append(brand_table)
    elements.append(Spacer(1, 8))
    
    elements.append(Paragraph(f"<b>Brand Positioning Statement:</b> {report.branding_attributes.brand_positioning_statement or 'N/A'}", normal))
    elements.append(Spacer(1, 12))

    # Marketing Plan
    elements.append(Paragraph("<b>Marketing Plan</b>", section_style))
    elements.append(Paragraph(f"Marketing Budget: {format_currency(report.marketing_and_communication.marketing_budget)}", normal))
    elements.append(Paragraph(f"Rationale: {report.marketing_and_communication.rational}", normal))
    elements.append(Spacer(1, 8))

    # Integrated Marketing Activities with flexible wrapping
    elements.append(Paragraph("<b>Integrated Marketing Activities</b>", styles['Heading3']))
    marketing_data = [[
        Paragraph("<b>Activity Name</b>", cell_style), 
        Paragraph("<b>Budget Allocated</b>", cell_style), 
        Paragraph("<b>Objective</b>", cell_style), 
        Paragraph("<b>Measurement</b>", cell_style), 
        Paragraph("<b>Target Journey</b>", cell_style)
    ]]
    for activity in report.integrated_marketing:
        marketing_data.append([
            Paragraph(str(activity.activity_name or "N/A"), cell_style),
            Paragraph(format_currency(activity.budget_allocated) if activity.budget_allocated else "N/A", cell_style),
            Paragraph(str(activity.objective or "N/A"), cell_style),
            Paragraph(str(activity.measurment or "N/A"), cell_style),
            Paragraph(str(activity.target_shopper_journey or "N/A"), cell_style)
        ])
    
    marketing_table = Table(marketing_data)
    marketing_table.setStyle(TableStyle([
        ("GRID", (0, 0), (-1, -1), 1, colors.black),
        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
        ("ALIGN", (0, 0), (-1, -1), "LEFT"),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("FONTSIZE", (0, 0), (-1, -1), 8),
    ]))
    elements.append(marketing_table)
    elements.append(Spacer(1, 8))

    # Competitor Analysis with flexible table
    elements.append(Paragraph("<b>Competitor Analysis</b>", styles['Heading3']))
    competitor_data = [
        [Paragraph("<b>Reference Retailer</b>", cell_style), Paragraph(str(report.marketing_competitor.name_of_the_reference_retailer or "N/A"), cell_style)],
        [Paragraph("<b>Marketing Communication</b>", cell_style), Paragraph(str(report.marketing_competitor.marketing_communication or "N/A"), cell_style)],
        [Paragraph("<b>Plan Activities</b>", cell_style), Paragraph(str(report.marketing_competitor.plan_activities or "N/A"), cell_style)]
    ]
    competitor_table = Table(competitor_data)
    competitor_table.setStyle(TableStyle([
        ("GRID", (0, 0), (-1, -1), 1, colors.black),
        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
        ("ALIGN", (0, 0), (-1, -1), "LEFT"),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
    ]))
    elements.append(competitor_table)
    elements.append(Spacer(1, 12))

    # Brand Journey (Optimising Assets) with flexible table - Start on new page
    elements.append(PageBreak())
    elements.append(Paragraph("<b>Brand Journey</b>", section_style))
    for i, asset in enumerate(report.optimising_assets, 1):
        elements.append(Paragraph(f"<b>Asset Optimization Record {i}</b>", styles['Heading3']))
        asset_data = [
            [Paragraph("<b>Space Resources</b>", cell_style), Paragraph(str(asset.space_resources_for_income or "N/A"), cell_style)],
            [Paragraph("<b>Non-Space Resources</b>", cell_style), Paragraph(str(asset.non_space_resources_for_income or "N/A"), cell_style)],
            [Paragraph("<b>Percentage of Sales</b>", cell_style), Paragraph(f"{asset.percentage_of_sales or 0}%", cell_style)],
            [Paragraph("<b>Predictions</b>", cell_style), Paragraph(str(asset.predictions_around_changes or "N/A"), cell_style)],
            [Paragraph("<b>Marketing Changes</b>", cell_style), Paragraph(str(asset.changes_in_marketing_communication or "N/A"), cell_style)]
        ]
        asset_table = Table(asset_data)
        asset_table.setStyle(TableStyle([
            ("GRID", (0, 0), (-1, -1), 1, colors.black),
            ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("VALIGN", (0, 0), (-1, -1), "TOP"),
            ("FONTSIZE", (0, 0), (-1, -1), 9),
        ]))
        elements.append(asset_table)
        elements.append(Spacer(1, 8))
    elements.append(Spacer(1, 12))




    # Build PDF
    pdf.build(elements)
    buffer.seek(0)
    filename = f"module7_report_{group_id}.pdf"

    return Response(
        content=buffer.getvalue(),
        media_type="application/pdf",
        headers={"Content-Disposition": f"attachment; filename={filename}"}
    )
@module_7_report_router.get("/{group_id}/preview-report-pdf7")
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 = Module7ReportService(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)}")