from fastapi import APIRouter, Depends, Response, HTTPException
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_2.schema import Module2ReportPreview
from app.api.module_2.service import Module2ReportService
from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student

module_2_report_router = APIRouter()


@module_2_report_router.get("/{group_id}/preview2", response_model=Module2ReportPreview)
async def preview_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Preview Module 2 Location Analysis report data"""
    service = Module2ReportService(db, token)
    return await service._fetch_module2_data(group_id)


@module_2_report_router.get("/{group_id}/download2")
async def download_report(
    group_id: int,
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    """Download Module 2 Location Analysis report as PDF"""
    service = Module2ReportService(db, token)
    report = await service._fetch_module2_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['Heading2'],
        alignment=1  # Center alignment
    )
    section_style = styles['Heading4']
    normal = styles['Normal']

    # 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 2: Location Analysis", title_style))
    elements.append(Spacer(1, 12))

    # Understanding Shoppers
    elements.append(Paragraph("<b>Understanding Shoppers</b>", section_style))
    elements.append(Paragraph("• Shopping Frequency per Month", normal))
    elements.append(Paragraph("• Household Consumption per Month", normal))
    elements.append(Paragraph("• Total Household Consumption per Month", normal))
    elements.append(Spacer(1, 6))

    # Catchment Potential
    elements.append(Paragraph("<b>Catchment Potential</b>", section_style))
    elements.append(Spacer(1, 12))
    catchment_data = [["ISEC Category", "Percentage of Segment", "Number of Potential Households"]]
    for c in report.catchment_potential:
        catchment_data.append([
            str(c.ISEC_Segment or ""), 
            f"{c.percentage_of_segment or 0.0}%",
            str(c.potential_number_of_households or "")
        ])
    catchment_table = Table(catchment_data, colWidths=[105, 150, 180])
    catchment_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"),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
    ]))
    elements.append(catchment_table)
    elements.append(Spacer(1, 12))
    est_market = getattr(report, "estimated_market_share", 0.0)
    elements.append(Paragraph(f"Estimated Market Share: {est_market}%", normal))
    elements.append(Spacer(1, 12))

    # Competition Intensity
    elements.append(Paragraph("<b>Competition Intensity</b>", section_style))
    elements.append(Paragraph("• Total Square foot of the competition", normal))
    total_competition = getattr(report, "total_sqft_of_competition", "N/A")
    elements.append(Paragraph(f"{total_competition}", normal))
    elements.append(Spacer(1, 6))

    # Quality of Location
    elements.append(Paragraph("<b>Quality of Location</b>", section_style))
    elements.append(Paragraph("• Spillage Factor", normal))
    spillage = getattr(report, "spillage_factor", "N/A")
    elements.append(Paragraph(f"{spillage}", normal))
    elements.append(Spacer(1, 6))

    # Location Definition
    elements.append(Paragraph("<b>Location Definition</b>", section_style))
    for location in report.location_details:
        fmt = location.store_format_type or "A"
        elements.append(Paragraph(f"Store Format: {fmt}", normal))
        elements.append(Paragraph(f"• Trading Radius: {location.trading_radius or 0.0}", normal))
        elements.append(Paragraph("• Adjacencies", normal))
        elements.append(Paragraph("• Corner Property", normal))
        elements.append(Paragraph("• Highstreet", normal))
        elements.append(Paragraph("• Mall", normal))
        elements.append(Paragraph("• Parking Space", normal))
        elements.append(Spacer(1, 4))
    elements.append(Spacer(1, 6))

    # Estimated Sales Table - Start on new page
    elements.append(PageBreak())
    elements.append(Paragraph("<b>Estimated Sales</b>", section_style))
    elements.append(Spacer(1, 12))
    sales_data = [["Estimated Sales", "Store A", "Store B"]]
    sale_a = getattr(report, "estimated_sales_a", 0.0)
    sale_b = getattr(report, "estimated_sales_b", 0.0)
    sales_data.append(["", f"Rs.{sale_a:,.2f}", f"Rs.{sale_b:,.2f}"])
    sales_table = Table(sales_data, colWidths=[120, 120, 120])
    sales_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"),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
    ]))
    elements.append(sales_table)
    elements.append(Spacer(1, 12))

    # Rent Details - Start on new page
    elements.append(Paragraph("<b>Rent Details</b>", section_style))
    for rent in report.rent_expenses:
        fmt = rent.store_format_type or "A"
        elements.append(Paragraph(f"Store Format: {fmt}", normal))
        elements.append(Paragraph(f"• Rental Advance Amount (in Rupees): {rent.rental_advance_amount or 0}", normal))
        elements.append(Paragraph(f"• Rental Advance Period (in Months): {rent.rental_advance_period or 0}", normal))
        elements.append(Paragraph(f"• Rent per Month (in Rupees): {rent.rent_per_month or 0}", normal))
        elements.append(Spacer(1, 4))
    elements.append(Spacer(1, 8))

    pdf.build(elements)
    buffer.seek(0)
    filename = f"module2_location_analysis_{group_id}.pdf"

    return Response(
        content=buffer.getvalue(),
        media_type="application/pdf",
        headers={"Content-Disposition": f"attachment; filename={filename}"}
    )


@module_2_report_router.get("/{group_id}/preview-report-pdf2")
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 = Module2ReportService(db,token)
        file_path = await service.generate_and_save_pdf(group_id)
        
        return {
            "group_id": group_id,
            "file_path": file_path,
        }
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")
