from __future__ import annotations

from pathlib import Path

from reportlab.lib.units import inch
from reportlab.platypus import Image, Paragraph, Table, TableStyle

from app.models import CompanySetting

ASSETS_DIR = Path(__file__).resolve().parent / "assets"
LOGO_PATH = ASSETS_DIR / "launch-logo.png"


def _company_block(company: CompanySetting | None) -> list[str]:
    company = company or CompanySetting()
    name = company.company_name or "SELFIE PETTI"
    address = (company.address or "Tamil Nadu, India").replace("\n", "<br/>")
    phone = company.phone or "9043717464"
    email = company.email or "selfiepetti@gmail.com"
    gstin = company.gstin or ""
    website = (company.website or "www.selfiepetti.com").replace("https://", "").replace("http://", "")
    lines = [
        f"<b>{name.upper()}</b>",
        address,
        f"Ph.: +91-{phone} | Email: {email}",
    ]
    if gstin:
        lines.append(f"GST No. - {gstin}")
    lines.append(f"{website} | {phone}")
    return lines


def _logo_image(*, max_width: float = 2.45 * inch, max_height: float = 0.95 * inch) -> Image | None:
    if not LOGO_PATH.is_file():
        return None
    img = Image(str(LOGO_PATH))
    width_ratio = max_width / float(img.imageWidth)
    height_ratio = max_height / float(img.imageHeight)
    scale = min(width_ratio, height_ratio)
    img.drawWidth = float(img.imageWidth) * scale
    img.drawHeight = float(img.imageHeight) * scale
    img.hAlign = "RIGHT"
    return img


def build_pdf_header_table(*, company: CompanySetting | None, normal_style, right_style) -> Table:
    header_left = Paragraph("<br/>".join(_company_block(company)), normal_style)
    logo = _logo_image()
    if logo is not None:
        header_right = logo
    else:
        header_right = Paragraph(
            "<b><font color='#A42FD8'>SELFIE</font> <font color='#123F9A'>PETTI</font></b><br/>"
            "<i>Memories that Remains in your Heart</i>",
            right_style,
        )
    header_table = Table(
        [[header_left, header_right]],
        colWidths=[4.1 * inch, 2.5 * inch],
    )
    header_table.setStyle(
        TableStyle(
            [
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("ALIGN", (1, 0), (1, 0), "RIGHT"),
                ("LEFTPADDING", (0, 0), (-1, -1), 0),
                ("RIGHTPADDING", (0, 0), (-1, -1), 0),
                ("TOPPADDING", (0, 0), (-1, -1), 0),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 0),
            ]
        )
    )
    return header_table
