"""
Auto-Invoice PDF Generator for XLancer Platform.
Generates professional English invoices using ReportLab.
"""
import os
import logging
from datetime import datetime

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, HRFlowable

logger = logging.getLogger(__name__)

INVOICES_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "invoices")
os.makedirs(INVOICES_DIR, exist_ok=True)

# ── Color Palette ────────────────────────────────────────────────────
BRAND_BLUE = colors.HexColor("#1a73e8")
BRAND_DARK = colors.HexColor("#1e293b")
LIGHT_GRAY = colors.HexColor("#f1f5f9")
BORDER_GRAY = colors.HexColor("#cbd5e1")
SUCCESS_GREEN = colors.HexColor("#16a34a")
REFUND_RED = colors.HexColor("#dc2626")


async def generate_invoice_pdf(
    project_id: int,
    project_title: str,
    client_id: int,
    client_name: str,
    freelancer_id: int,
    freelancer_name: str,
    amount: int,
    commission: int,
    payout: int,
    commission_pct: int,
    milestone_title: str = None,
    milestone_id: int = None,
    is_refund: bool = False,
    promo_discount: int = 0,
) -> str:
    """
    Generate a professional invoice PDF and return its file path.
    """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    suffix = "refund" if is_refund else "invoice"
    filename = f"{suffix}_{project_id}_{timestamp}.pdf"
    filepath = os.path.join(INVOICES_DIR, filename)

    doc = SimpleDocTemplate(
        filepath,
        pagesize=A4,
        rightMargin=20 * mm,
        leftMargin=20 * mm,
        topMargin=15 * mm,
        bottomMargin=15 * mm,
    )

    styles = getSampleStyleSheet()
    
    # Custom styles
    title_style = ParagraphStyle(
        "InvoiceTitle",
        parent=styles["Heading1"],
        fontSize=22,
        textColor=BRAND_DARK,
        spaceAfter=4,
    )
    subtitle_style = ParagraphStyle(
        "InvoiceSubtitle",
        parent=styles["Normal"],
        fontSize=10,
        textColor=colors.gray,
        spaceAfter=12,
    )
    section_style = ParagraphStyle(
        "SectionHeader",
        parent=styles["Heading2"],
        fontSize=13,
        textColor=BRAND_BLUE,
        spaceBefore=14,
        spaceAfter=6,
    )
    normal_style = ParagraphStyle(
        "NormalText",
        parent=styles["Normal"],
        fontSize=10,
        textColor=BRAND_DARK,
        leading=14,
    )
    footer_style = ParagraphStyle(
        "FooterText",
        parent=styles["Normal"],
        fontSize=8,
        textColor=colors.gray,
        alignment=1,  # center
    )

    elements = []

    # ── Header ─────────────────────────────────────────────────────
    invoice_type = "REFUND RECEIPT" if is_refund else "INVOICE"
    status_color = REFUND_RED if is_refund else SUCCESS_GREEN
    
    elements.append(Paragraph(f"XLancer — {invoice_type}", title_style))
    
    invoice_number = f"INV-{project_id}-{timestamp[-6:]}"
    date_str = datetime.now().strftime("%Y-%m-%d %H:%M")
    elements.append(Paragraph(f"Invoice #: {invoice_number}  |  Date: {date_str}", subtitle_style))
    
    elements.append(HRFlowable(
        width="100%", thickness=1, color=BORDER_GRAY,
        spaceAfter=10, spaceBefore=2
    ))

    # ── Parties Info ───────────────────────────────────────────────
    elements.append(Paragraph("Parties", section_style))
    
    parties_data = [
        ["Role", "Name", "User ID"],
        ["Client (Employer)", str(client_name), str(client_id)],
        ["Freelancer", str(freelancer_name), str(freelancer_id)],
    ]
    parties_table = Table(parties_data, colWidths=[45 * mm, 70 * mm, 45 * mm])
    parties_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), BRAND_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("BACKGROUND", (0, 1), (-1, -1), LIGHT_GRAY),
        ("GRID", (0, 0), (-1, -1), 0.5, BORDER_GRAY),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
    ]))
    elements.append(parties_table)

    # ── Project Details ────────────────────────────────────────────
    elements.append(Paragraph("Project Details", section_style))
    
    proj_data = [
        ["Field", "Value"],
        ["Project ID", f"#{project_id}"],
        ["Project Title", str(project_title)],
    ]
    if milestone_title:
        proj_data.append(["Milestone", f"#{milestone_id} — {milestone_title}"])
    
    proj_table = Table(proj_data, colWidths=[45 * mm, 115 * mm])
    proj_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), BRAND_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("BACKGROUND", (0, 1), (-1, -1), colors.white),
        ("GRID", (0, 0), (-1, -1), 0.5, BORDER_GRAY),
        ("ALIGN", (0, 0), (0, -1), "LEFT"),
        ("ALIGN", (1, 0), (1, -1), "LEFT"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
    ]))
    elements.append(proj_table)

    # ── Financial Summary ──────────────────────────────────────────
    elements.append(Paragraph("Financial Summary", section_style))
    
    if is_refund:
        fin_data = [
            ["Description", "Amount (Tomans)"],
            ["Refunded to Client", f"{amount:,}"],
        ]
        if promo_discount > 0:
            fin_data.append(["Promo Discount Applied", f"-{promo_discount:,}"])
        fin_data.append(["Total Refund", f"{amount:,}"])
    else:
        fin_data = [
            ["Description", "Amount (Tomans)"],
            ["Gross Project Value", f"{amount:,}"],
            [f"Platform Commission ({commission_pct}%)", f"-{commission:,}"],
        ]
        if promo_discount > 0:
            fin_data.append(["Promo Discount Applied", f"-{promo_discount:,}"])
        fin_data.append(["Net Payout to Freelancer", f"{payout:,}"])
    
    fin_table = Table(fin_data, colWidths=[100 * mm, 60 * mm])
    total_row = len(fin_data) - 1
    fin_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), BRAND_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("BACKGROUND", (0, 1), (-1, total_row - 1), colors.white),
        ("BACKGROUND", (0, total_row), (-1, total_row), LIGHT_GRAY),
        ("FONTNAME", (0, total_row), (-1, total_row), "Helvetica-Bold"),
        ("TEXTCOLOR", (1, total_row), (1, total_row), status_color),
        ("GRID", (0, 0), (-1, -1), 0.5, BORDER_GRAY),
        ("ALIGN", (1, 0), (1, -1), "RIGHT"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
    ]))
    elements.append(fin_table)

    # ── Status ─────────────────────────────────────────────────────
    elements.append(Spacer(1, 12))
    status_text = "REFUNDED" if is_refund else "PAID"
    elements.append(Paragraph(
        f'<font color="{status_color.hexval()}" size="14"><b>Status: {status_text}</b></font>',
        ParagraphStyle("Status", parent=styles["Normal"], alignment=1)
    ))

    # ── Footer ─────────────────────────────────────────────────────
    elements.append(Spacer(1, 30))
    elements.append(HRFlowable(
        width="100%", thickness=0.5, color=BORDER_GRAY,
        spaceAfter=6, spaceBefore=0
    ))
    elements.append(Paragraph(
        "This is an automatically generated invoice by XLancer Freelance Marketplace Bot.<br/>"
        "For support, contact @xlancer_support on Telegram.",
        footer_style
    ))

    # Build PDF
    try:
        doc.build(elements)
        logger.info(f"Invoice generated: {filepath}")
        return filepath
    except Exception as e:
        logger.error(f"Failed to generate invoice: {e}")
        return None
