import os
import html
from decimal import Decimal

from flask import current_app
from app.utils import indian_amount
from reportlab.lib import colors
from reportlab.lib.enums import TA_RIGHT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, KeepTogether,
)


def _money(value):
    return indian_amount(value)


def generate_system_vendor_invoice_pdf(invoice, selected_rows):
    """Create the electronically confirmed vendor invoice PDF."""
    root = os.path.join(current_app.root_path, "static", "uploads", "vendor_invoices")
    os.makedirs(root, exist_ok=True)

    filename = f"system_vendor_invoice_{invoice.id}.pdf"
    path = os.path.join(root, filename)

    doc = SimpleDocTemplate(
        path,
        pagesize=A4,
        rightMargin=16*mm,
        leftMargin=16*mm,
        topMargin=15*mm,
        bottomMargin=15*mm,
        title=f"Vendor Invoice {invoice.vendor_invoice_no}",
        author="Crystal Nexus Vendor Portal",
    )

    styles = getSampleStyleSheet()
    title = ParagraphStyle(
        "InvoiceTitle", parent=styles["Title"], fontSize=21, leading=25,
        textColor=colors.HexColor("#103A71"), spaceAfter=4,
    )
    muted = ParagraphStyle(
        "Muted", parent=styles["BodyText"], fontSize=8.5, leading=11,
        textColor=colors.HexColor("#6D7788"),
    )
    body = ParagraphStyle(
        "Body", parent=styles["BodyText"], fontSize=9, leading=12,
        textColor=colors.HexColor("#172033"),
    )
    right = ParagraphStyle(
        "Right", parent=body, alignment=TA_RIGHT,
    )
    sign = ParagraphStyle(
        "Sign", parent=body, fontSize=10, leading=14,
        textColor=colors.HexColor("#103A71"),
    )

    story = []
    vendor = invoice.vendor
    story.append(Paragraph("VENDOR INVOICE", title))
    story.append(Paragraph("Generated through Crystal Nexus Vendor Portal", muted))
    story.append(Spacer(1, 6*mm))

    # Prefer immutable invoice snapshots. Older invoices (raised before this
    # feature) fall back to the vendor's current billing profile and linked
    # customer-invoice branch so they can be regenerated once the profile is
    # completed.
    profile = getattr(vendor, "billing_profile", None)
    legacy_branch = None
    if not invoice.bill_to_address:
        for item in invoice.items or []:
            if item.customer_invoice and item.customer_invoice.company_branch:
                legacy_branch = item.customer_invoice.company_branch
                break

    bill_to_company = invoice.bill_to_company_name or (legacy_branch.company.name if legacy_branch and legacy_branch.company else "Crystal Hues")
    bill_to_branch = invoice.bill_to_branch_name or (legacy_branch.branch_name if legacy_branch else "")
    bill_to_address = invoice.bill_to_address or (legacy_branch.branch_address if legacy_branch else "")
    bill_to_gst = invoice.bill_to_gst_no or (legacy_branch.gst_no if legacy_branch else "")
    branch_markers = [bill_to_branch]
    if legacy_branch is not None:
        branch_markers.extend([
            getattr(legacy_branch, "branch_code", None),
            getattr(legacy_branch, "tally_company_name", None),
        ])
    nsez_gst_exempt = any("NSEZ" in str(value or "").upper() for value in branch_markers)

    beneficiary_name = invoice.vendor_beneficiary_name or (profile.beneficiary_name if profile else None) or vendor.name
    billing_address = invoice.vendor_billing_address or (profile.billing_address if profile else None) or ""

    def esc(value):
        return html.escape(str(value or "")).replace("\n", "<br/>")

    to_text = f"<b>TO</b><br/><b>{esc(bill_to_company)}</b>"
    if bill_to_branch:
        to_text += f"<br/>{esc(bill_to_branch)}"
    if bill_to_address:
        to_text += f"<br/>{esc(bill_to_address)}"
    if bill_to_gst:
        to_text += f"<br/><b>GSTIN:</b> {esc(bill_to_gst)}"

    from_text = f"<b>FROM</b><br/><b>{esc(beneficiary_name)}</b>"
    if billing_address:
        from_text += f"<br/>{esc(billing_address)}"
    from_text += f"<br/><b>TransId:</b> {esc(vendor.external_translator_id)}"
    if vendor.email:
        from_text += f"<br/>{esc(vendor.email)}"
    if vendor.phone:
        from_text += f"<br/>{esc(vendor.phone)}"
    pan_number = invoice.vendor_pan_number or (profile.pan_number if profile else None)
    vendor_gstin = invoice.vendor_gstin or (profile.gstin if profile else None)
    if pan_number:
        from_text += f"<br/><b>PAN:</b> {esc(pan_number)}"
    if invoice.vendor_gst_registered or (invoice.vendor_gst_registered is None and profile and profile.gst_registered):
        if vendor_gstin:
            from_text += f"<br/><b>GSTIN:</b> {esc(vendor_gstin)}"

    party_info = Table([[Paragraph(to_text, body), Paragraph(from_text, body)]], colWidths=[88*mm, 88*mm])
    party_info.setStyle(TableStyle([
        ('VALIGN',(0,0),(-1,-1),'TOP'),
        ('BOX',(0,0),(-1,-1),0.7,colors.HexColor('#E3E9F2')),
        ('INNERGRID',(0,0),(-1,-1),0.5,colors.HexColor('#E3E9F2')),
        ('BACKGROUND',(0,0),(-1,-1),colors.HexColor('#F8FAFD')),
        ('LEFTPADDING',(0,0),(-1,-1),10),('RIGHTPADDING',(0,0),(-1,-1),10),
        ('TOPPADDING',(0,0),(-1,-1),9),('BOTTOMPADDING',(0,0),(-1,-1),9),
    ]))
    story.append(party_info)
    story.append(Spacer(1, 4*mm))

    inv_text = (
        f"<b>Invoice No:</b> {esc(invoice.vendor_invoice_no)}<br/>"
        f"<b>Invoice Date:</b> {invoice.invoice_date.strftime('%d %b %Y')}<br/>"
        f"<b>Due Date:</b> {invoice.due_date.strftime('%d %b %Y') if invoice.due_date else '—'}<br/>"
        f"<b>Currency:</b> {esc(invoice.currency)}"
    )
    info = Table([[Paragraph("<b>INVOICE DETAILS</b>", body), Paragraph(inv_text, right)]], colWidths=[88*mm, 88*mm])
    info.setStyle(TableStyle([
        ('VALIGN',(0,0),(-1,-1),'TOP'),
        ('BOX',(0,0),(-1,-1),0.7,colors.HexColor('#E3E9F2')),
        ('INNERGRID',(0,0),(-1,-1),0,colors.white),
        ('BACKGROUND',(0,0),(-1,-1),colors.HexColor('#F8FAFD')),
        ('LEFTPADDING',(0,0),(-1,-1),10),('RIGHTPADDING',(0,0),(-1,-1),10),
        ('TOPPADDING',(0,0),(-1,-1),9),('BOTTOMPADDING',(0,0),(-1,-1),9),
    ]))
    story.append(info)
    story.append(Spacer(1, 6*mm))

    data = [["Jobcard", "Service", "Customer Invoice", "Qty", "Rate", "Amount"]]
    if selected_rows is not None:
        for assignment, service, jobcard, customer_invoice in selected_rows:
            amount = Decimal(str(assignment.rate or 0)) if assignment.flat_rate else Decimal(str(assignment.assigned_qty or 0))*Decimal(str(assignment.rate or 0))
            data.append([
                jobcard.jobcard_code or "—",
                service.service_name or "—",
                customer_invoice.invoice_no or "—",
                str(assignment.assigned_qty or 0),
                f"{invoice.currency} {_money(assignment.rate)}" + (" Flat" if assignment.flat_rate else ""),
                f"{invoice.currency} {_money(amount)}",
            ])
    else:
        # Regeneration path for an already-raised system invoice. This keeps
        # downloaded PDFs aligned with the current TDS rounding rule.
        for item in invoice.items:
            data.append([
                item.jobcard_code or "—",
                item.service_name or "—",
                item.customer_invoice.invoice_no if item.customer_invoice else "—",
                str(item.quantity or 0),
                f"{invoice.currency} {_money(item.rate)}" + (" Flat" if item.flat_rate else ""),
                f"{invoice.currency} {_money(item.amount)}",
            ])

    tbl = Table(data, repeatRows=1, colWidths=[29*mm, 35*mm, 32*mm, 18*mm, 31*mm, 31*mm])
    tbl.setStyle(TableStyle([
        ('BACKGROUND',(0,0),(-1,0),colors.HexColor('#103A71')),
        ('TEXTCOLOR',(0,0),(-1,0),colors.white),
        ('FONTNAME',(0,0),(-1,0),'Helvetica-Bold'),
        ('FONTSIZE',(0,0),(-1,0),8),
        ('FONTSIZE',(0,1),(-1,-1),8),
        ('TEXTCOLOR',(0,1),(-1,-1),colors.HexColor('#172033')),
        ('GRID',(0,0),(-1,-1),0.45,colors.HexColor('#E3E9F2')),
        ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
        ('ALIGN',(3,1),(-1,-1),'RIGHT'),
        ('LEFTPADDING',(0,0),(-1,-1),5),('RIGHTPADDING',(0,0),(-1,-1),5),
        ('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7),
        ('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,colors.HexColor('#FBFCFE')]),
    ]))
    story.append(tbl)
    story.append(Spacer(1, 5*mm))

    taxable = invoice.calculated_taxable_amount
    total_rows = [[Paragraph("Taxable / Service Value", body), Paragraph(f"<b>{invoice.currency} {_money(taxable)}</b>", right)]]
    if invoice.gst_registered and Decimal(str(invoice.gst_amount or 0)) > 0:
        total_rows.append([Paragraph(f"GST @ {_money(invoice.gst_rate)}%", body), Paragraph(f"<b>INR {_money(invoice.gst_amount)}</b>", right)])
    elif nsez_gst_exempt and (invoice.currency or "").strip().upper() == "INR":
        total_rows.append([Paragraph("GST", body), Paragraph("<b>Exempt - NSEZ branch</b>", right)])
    total_rows.append([Paragraph("Total Invoice Amount", body), Paragraph(f"<b>{invoice.currency} {_money(invoice.total_amount)}</b>", right)])
    if (invoice.currency or "").strip().upper() == "INR":
        tds = invoice.calculated_tds_amount
        net = invoice.calculated_net_payable_amount
        tds_label = "TDS @ 10% on taxable value (GST excluded)" if invoice.gst_registered else "TDS @ 10% (deducted at payment)"
        total_rows.append([Paragraph(tds_label, body), Paragraph(f"<b>INR {_money(tds)}</b>", right)])
        total_rows.append([Paragraph("Net Payable after TDS", body), Paragraph(f"<b>INR {_money(net)}</b>", right)])
    total = Table(total_rows, colWidths=[120*mm,56*mm])
    total.setStyle(TableStyle([
        ('BACKGROUND',(0,0),(-1,-1),colors.HexColor('#FFF3E9')),
        ('BOX',(0,0),(-1,-1),0.7,colors.HexColor('#F4C99F')),
        ('LEFTPADDING',(0,0),(-1,-1),10),('RIGHTPADDING',(0,0),(-1,-1),10),
        ('TOPPADDING',(0,0),(-1,-1),9),('BOTTOMPADDING',(0,0),(-1,-1),9),
    ]))
    story.append(total)
    story.append(Spacer(1, 6*mm))

    bank_name = invoice.vendor_bank_name or (profile.bank_name if profile else None)
    bank_address = invoice.vendor_bank_address or (profile.bank_address if profile else None)
    account_number = invoice.vendor_bank_account_number or (profile.bank_account_number if profile else None)
    ifsc_code = invoice.vendor_ifsc_code or (profile.ifsc_code if profile else None)
    swift_code = invoice.vendor_swift_code or (profile.swift_code if profile else None)
    iban = invoice.vendor_iban or (profile.iban if profile else None)
    paypal_id = invoice.vendor_paypal_id or (profile.paypal_id if profile else None)

    payment_rows = [[Paragraph("<b>PAYMENT / BANK DETAILS</b>", body), ""]]
    for label, value in (
        ("Beneficiary Name", beneficiary_name),
        ("Bank Name", bank_name),
        ("Bank Address", bank_address),
        ("Account Number", account_number),
        ("IFSC Code", ifsc_code),
        ("SWIFT / BIC", swift_code),
        ("IBAN", iban),
        ("PayPal ID", paypal_id),
    ):
        if value:
            payment_rows.append([Paragraph(f"<b>{label}</b>", body), Paragraph(esc(value), body)])

    payment_table = Table(payment_rows, colWidths=[52*mm,124*mm])
    payment_table.setStyle(TableStyle([
        ('SPAN',(0,0),(1,0)),
        ('BACKGROUND',(0,0),(-1,0),colors.HexColor('#EEF4FB')),
        ('BOX',(0,0),(-1,-1),0.7,colors.HexColor('#D8E2EF')),
        ('INNERGRID',(0,1),(-1,-1),0.4,colors.HexColor('#E5EBF3')),
        ('VALIGN',(0,0),(-1,-1),'TOP'),
        ('LEFTPADDING',(0,0),(-1,-1),8),('RIGHTPADDING',(0,0),(-1,-1),8),
        ('TOPPADDING',(0,0),(-1,-1),6),('BOTTOMPADDING',(0,0),(-1,-1),6),
    ]))
    story.append(payment_table)
    story.append(Spacer(1, 9*mm))

    confirmation = [
        Paragraph("Electronic Confirmation", styles['Heading3']),
        Paragraph(
            "The vendor confirmed that the jobs and commercial values shown above are correct and authorized Crystal Nexus to create this invoice on the vendor's behalf.",
            body,
        ),
        Spacer(1, 3*mm),
        Paragraph(f"Confirmed / signed electronically by: <b>{invoice.signature_name}</b>", sign),
        Paragraph(
            f"Confirmation timestamp: {invoice.signature_confirmed_at.strftime('%d %b %Y, %I:%M %p UTC') if invoice.signature_confirmed_at else '—'}",
            muted,
        ),
    ]
    story.append(KeepTogether(confirmation))
    story.append(Spacer(1, 10*mm))
    story.append(Paragraph("This invoice was generated electronically through Crystal Nexus Vendor Portal.", muted))

    doc.build(story)
    return filename, f"uploads/vendor_invoices/{filename}", path
