"""PDF documents (statement of account, invoice) for download and email, in English or Arabic (right to left)."""
import io
import os
import re
from xml.sax.saxutils import escape

import arabic_reshaper
from bidi.algorithm import get_display
from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT, TA_RIGHT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle

from .i18n import get_lang, nm, t
from .money import fmt

FONT_DIR = os.path.join(os.path.dirname(__file__), "static", "fonts")
ARABIC = re.compile("[؀-ۿݐ-ݿﭐ-﷿ﹰ-﻿]")
INK, MUTED, LINE, SOFT = colors.HexColor("#0f1729"), colors.HexColor("#6b7489"), colors.HexColor("#e5e7ef"), \
    colors.HexColor("#f7f8fb")
_fonts = False


def _register():
    global _fonts
    if not _fonts:
        pdfmetrics.registerFont(TTFont("Plex", os.path.join(FONT_DIR, "IBMPlexSansArabic-Regular.ttf")))
        pdfmetrics.registerFont(TTFont("Plex-Bold", os.path.join(FONT_DIR, "IBMPlexSansArabic-Bold.ttf")))
        pdfmetrics.registerFontFamily("Plex", normal="Plex", bold="Plex-Bold")
        _fonts = True


class Visual(str):
    """Text already in display order (see kv); not shaped again."""


def shape(text):
    """Arabic letters joined and laid out right to left, as PDF text is drawn left to right."""
    if isinstance(text, Visual):
        return text
    text = "" if text is None else str(text)
    return get_display(arabic_reshaper.reshape(text)) if ARABIC.search(text) else text


def wrap_logical(text, font, size, width):
    """Break text into lines before it is reordered right to left; wrapping the reordered text would put the
    lines in reverse order."""
    out = []
    for para in text.split("\n"):
        line = ""
        for word in para.split(" "):
            trial = f"{line} {word}" if line else word
            if line and pdfmetrics.stringWidth(shape(trial), font, size) > width:
                out.append(line)
                line = word
            else:
                line = trial
        out.append(line)
    return out


class BidiParagraph(Paragraph):
    def __init__(self, text, style):
        self.raw = text
        super().__init__(escape(shape(text)).replace("\n", "<br/>"), style)

    def wrap(self, avail_width, avail_height):
        if not isinstance(self.raw, Visual) and ARABIC.search(self.raw):
            lines = wrap_logical(self.raw, self.style.fontName, self.style.fontSize, avail_width - 2)
            Paragraph.__init__(self, "<br/>".join(escape(shape(ln)) for ln in lines), self.style)
        return super().wrap(avail_width, avail_height)


class Doc:
    """Shared page setup: styles that follow the language direction, the accent colour, header and footer."""

    def __init__(self, company, title, title_en=None):
        _register()
        self.title_en = title_en
        self.rtl = get_lang() == "ar"
        self.company = company
        self.title = title
        self.accent = colors.HexColor(company["accent"] or "#4f46e5") if company["accent"] else colors.HexColor("#4f46e5")
        align = TA_RIGHT if self.rtl else TA_LEFT
        self.st = {
            "body": ParagraphStyle("body", fontName="Plex", fontSize=9, leading=12.5, textColor=INK, alignment=align),
            "small": ParagraphStyle("small", fontName="Plex", fontSize=8, leading=11, textColor=MUTED, alignment=align),
            "h1": ParagraphStyle("h1", fontName="Plex-Bold", fontSize=17, leading=21, textColor=INK, alignment=align),
            "h2": ParagraphStyle("h2", fontName="Plex-Bold", fontSize=10.5, leading=14, textColor=INK, alignment=align),
            "co": ParagraphStyle("co", fontName="Plex-Bold", fontSize=12, leading=15, textColor=self.accent, alignment=align),
            "num": ParagraphStyle("num", fontName="Plex", fontSize=8.5, leading=12, textColor=INK, alignment=TA_RIGHT),
            "td": ParagraphStyle("td", fontName="Plex", fontSize=8.5, leading=12, textColor=INK, alignment=align),
            "numb": ParagraphStyle("numb", fontName="Plex-Bold", fontSize=9.5, leading=13, textColor=INK, alignment=TA_RIGHT),
            "th": ParagraphStyle("th", fontName="Plex-Bold", fontSize=8, leading=10.5, textColor=MUTED, alignment=align),
            "thn": ParagraphStyle("thn", fontName="Plex-Bold", fontSize=8, leading=10.5, textColor=MUTED, alignment=TA_RIGHT),
        }

    def p(self, text, style="body"):
        return BidiParagraph("" if text is None else text, self.st[style])

    def kv(self, label, value):
        """'Label: value' with the label in the reading direction and dates or numbers kept as they are."""
        return Visual(f"{value} :{shape(label)}") if self.rtl else f"{label}: {value}"

    def join(self, parts):
        parts = [x for x in parts if x]
        return Visual("  ·  ".join(reversed(parts))) if self.rtl else "  ·  ".join(parts)

    def row(self, cells):
        """Columns in reading order: reversed for Arabic."""
        return list(reversed(cells)) if self.rtl else cells

    def widths(self, ws):
        return list(reversed(ws)) if self.rtl else ws

    def letterhead(self):
        """Logo, the company name in English and Arabic, CR / VAT and address, and the accent rule."""
        from reportlab.platypus import Image
        from .branding import logo_path
        c = self.company
        left = [BidiParagraph(c["name_en"], ParagraphStyle("le", parent=self.st["co"], alignment=TA_LEFT))]
        ids = "  ·  ".join(x for x in (f"CR {c['cr_no']}" if c["cr_no"] else "", f"VAT {c['vat_no']}" if c["vat_no"] else "") if x)
        small_l = ParagraphStyle("sl", parent=self.st["small"], alignment=TA_LEFT)
        small_r = ParagraphStyle("sr", parent=self.st["small"], alignment=TA_RIGHT)
        for line in (ids, (c["address_en"] or "").replace("\n", ", "), "  ·  ".join(x for x in (c["phone"], c["email"]) if x)):
            if line:
                left.append(BidiParagraph(line, small_l))
        right = [BidiParagraph(c["name_ar"] or "", ParagraphStyle("ra", parent=self.st["co"], alignment=TA_RIGHT,
                                                                   textColor=INK))]
        if c["address_ar"]:
            right.append(BidiParagraph(c["address_ar"].replace("\n", "، "), small_r))
        path = logo_path(c)
        cells, widths = [left, right], [90 * mm, 90 * mm]
        if path:
            from PIL import Image as PILImage
            with PILImage.open(path) as im:
                w, h = im.size
            lw = min(15 * mm * w / h, 52 * mm)
            cells, widths = [Image(path, width=lw, height=lw * h / w), left, right], [56 * mm, 62 * mm, 62 * mm]
        tbl = Table([cells], colWidths=widths)
        tbl.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                                 ("RIGHTPADDING", (0, 0), (-1, -1), 0)]))
        return [tbl, Spacer(1, 2.5 * mm), self.rule(), Spacer(1, 5 * mm)]

    def signatures(self):
        """Prepared by / Reviewed by / Approved by boxes, kept together at the end of a document."""
        from reportlab.platypus import KeepTogether
        tbl = signature_table(self.st["h2"], self.st["small"], 180 * mm)
        return KeepTogether([Spacer(1, 12 * mm), tbl])

    def header(self, right_lines):
        """Letterhead, then the document title with its details (number, dates...) under it."""
        from .i18n import AR
        story = self.letterhead()
        title = f"{self.title_en}  ·  {AR[self.title_en]}" if self.title_en in AR else self.title
        story.append(self.p(title, "h1"))
        for x in right_lines:
            story.append(self.p(self.kv(*x) if isinstance(x, tuple) else x, "small"))
        return story + [Spacer(1, 5 * mm)]

    def header_old(self, right_lines):
        c = self.company
        name = nm(c)
        left = [self.p(name, "co")]
        for line in ((c["address_ar"] if self.rtl and c["address_ar"] else c["address_en"]) or "").splitlines():
            left.append(self.p(line, "small"))
        bits = [self.kv(t("VAT"), c["vat_no"]) if c["vat_no"] else "", self.kv(t("CR"), c["cr_no"]) if c["cr_no"] else ""]
        if any(bits):
            left.append(self.p(self.join(bits), "small"))
        contact = self.join([c["phone"], c["email"]])
        if contact:
            left.append(self.p(contact, "small"))
        right = [self.p(self.title, "h1")] + [self.p(self.kv(*x) if isinstance(x, tuple) else x, "small")
                                               for x in right_lines]
        tbl = Table([self.row([left, right])], colWidths=self.widths([100 * mm, 80 * mm]))
        tbl.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                                 ("RIGHTPADDING", (0, 0), (-1, -1), 0)]))
        return [tbl, Spacer(1, 4 * mm), self.rule(), Spacer(1, 5 * mm)]

    def rule(self):
        tbl = Table([[""]], colWidths=[180 * mm], rowHeights=[2])
        tbl.setStyle(TableStyle([("LINEABOVE", (0, 0), (-1, -1), 1.5, self.accent)]))
        return tbl

    def grid(self, data, widths, head=True, total_rows=0, zebra=True):
        tbl = Table(data, colWidths=widths, repeatRows=1 if head else 0)
        style = [("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TOPPADDING", (0, 0), (-1, -1), 5),
                 ("BOTTOMPADDING", (0, 0), (-1, -1), 5), ("LEFTPADDING", (0, 0), (-1, -1), 4),
                 ("RIGHTPADDING", (0, 0), (-1, -1), 4), ("LINEBELOW", (0, 0), (-1, -1), 0.5, LINE)]
        if head:
            style += [("BACKGROUND", (0, 0), (-1, 0), SOFT), ("LINEBELOW", (0, 0), (-1, 0), 0.8, MUTED)]
        if zebra:
            for i in range(2 if head else 1, len(data) - total_rows, 2):
                style.append(("BACKGROUND", (0, i), (-1, i), colors.HexColor("#fbfbfd")))
        for i in range(len(data) - total_rows, len(data)):
            style += [("BACKGROUND", (0, i), (-1, i), SOFT), ("LINEABOVE", (0, i), (-1, i), 0.8, MUTED)]
        tbl.setStyle(TableStyle(style))
        return tbl

    def build(self, story):
        buf = io.BytesIO()
        doc = SimpleDocTemplate(buf, pagesize=A4, leftMargin=15 * mm, rightMargin=15 * mm, topMargin=12 * mm,
                                bottomMargin=18 * mm, title=self.title, author=nm(self.company))
        doc.build(story, canvasmaker=numbered_canvas(A4, 15 * mm, f"{nm(self.company)} · {self.title}"))
        return buf.getvalue()


def signature_table(head_style, small_style, width):
    """Three signature boxes with a gap between them: title, space to sign, a line, 'Name, signature and date'."""
    head = ParagraphStyle("sh", parent=head_style, alignment=1, fontSize=8.5)
    small = ParagraphStyle("ss", parent=small_style, alignment=1)
    gap = 10 * mm
    box = (width - 2 * gap) / 3
    labels = ("Prepared by", "Reviewed by", "Approved by")
    rows = [[BidiParagraph(t(labels[0]), head), "", BidiParagraph(t(labels[1]), head), "", BidiParagraph(t(labels[2]), head)],
            [""] * 5,
            [BidiParagraph(t("Name, signature and date"), small), "", BidiParagraph(t("Name, signature and date"), small), "",
             BidiParagraph(t("Name, signature and date"), small)]]
    tbl = Table(rows, colWidths=[box, gap, box, gap, box], rowHeights=[None, 15 * mm, None])
    tbl.setStyle(TableStyle([("LINEABOVE", (c, 2), (c, 2), 0.8, INK) for c in (0, 2, 4)] +
                            [("VALIGN", (0, 0), (-1, -1), "BOTTOM"), ("LEFTPADDING", (0, 0), (-1, -1), 2),
                             ("RIGHTPADDING", (0, 0), (-1, -1), 2)]))
    return tbl


def numbered_canvas(page, margin, running):
    """A canvas class whose pages end with who printed it and when, the document name and 'Page x of y'."""
    from reportlab.pdfgen import canvas as rl_canvas
    from .exports import printed_line
    printed, running, page_word, of_word = shape(printed_line()), shape(running), shape(t("Page")), shape(t("of"))

    class Numbered(rl_canvas.Canvas):
        def __init__(self, *a, **kw):
            super().__init__(*a, **kw)
            self._pages = []

        def showPage(self):
            self._pages.append(dict(self.__dict__))
            self._startPage()

        def save(self):
            total = len(self._pages)
            for st in self._pages:
                self.__dict__.update(st)
                self.saveState()
                self.setStrokeColor(LINE)
                self.setLineWidth(0.6)
                self.line(margin, 12 * mm, page[0] - margin, 12 * mm)
                self.setFont("Plex", 7)
                self.setFillColor(MUTED)
                self.drawString(margin, 8 * mm, printed)
                self.drawCentredString(page[0] / 2, 8 * mm, running)
                self.drawRightString(page[0] - margin, 8 * mm, f"{page_word} {self._pageNumber} {of_word} {total}")
                self.restoreState()
                super().showPage()
            super().save()
    return Numbered


def statement_pdf(company, partner, side, sections, date_from, date_to, decimals):
    """sections from statements.statement(); decimals: {currency: decimals}."""
    d = Doc(company, t("Statement of Account"), "Statement of Account")
    story = d.header([(t("Period"), f"{date_to} — {date_from}" if d.rtl else f"{date_from} — {date_to}"),
                      t("Customer") if side == "customer" else t("Vendor")])
    who = [d.p(nm(partner), "h2")]
    if partner["vat_no"]:
        who.append(d.p(d.kv(t("VAT"), partner["vat_no"]), "small"))
    if partner["address"]:
        who.append(d.p(partner["address"], "small"))
    if partner["email"]:
        who.append(d.p(partner["email"], "small"))
    story += who + [Spacer(1, 5 * mm)]
    if not sections:
        story.append(d.p(t("No transactions in this period.")))
    for sec in sections:
        cur, dec = sec["currency"], decimals.get(sec["currency"], 2)
        money = lambda v: fmt(v, dec)  # noqa: E731
        # summary boxes
        boxes = [(t("Opening balance"), sec["opening"]), (t("Debits"), sec["debit"]), (t("Credits"), sec["credit"]),
                 (t("Balance due") if side == "customer" else t("Balance payable"), sec["closing"])]
        cells = [[d.p(f"{lbl} ({cur})", "small"), d.p(money(v), "numb")] for lbl, v in boxes]
        summary = Table([d.row(cells)], colWidths=[45 * mm] * 4)
        summary.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.6, LINE), ("INNERGRID", (0, 0), (-1, -1), 0.6, LINE),
                                     ("BACKGROUND", (-1 if not d.rtl else 0, 0), (-1 if not d.rtl else 0, 0), SOFT),
                                     ("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 6),
                                     ("BOTTOMPADDING", (0, 0), (-1, -1), 6)]))
        story += [summary, Spacer(1, 5 * mm)]
        ws = [22 * mm, 26 * mm, 34 * mm, 32 * mm, 22 * mm, 22 * mm, 22 * mm]
        head = d.row([d.p(t("Date"), "th"), d.p(t("Document"), "th"), d.p(t("Number"), "th"), d.p(t("Details"), "th"),
                      d.p(t("Debit"), "thn"), d.p(t("Credit"), "thn"), d.p(t("Balance"), "thn")])
        data = [head, d.row([d.p(date_from, "td"), d.p(t("Opening balance"), "td"), d.p(""), d.p(""), d.p(""), d.p(""),
                             d.p(money(sec["opening"]), "num")])]
        for r in sec["lines"]:
            data.append(d.row([d.p(r["date"], "td"), d.p(t(r["doc"]), "td"), d.p(r["number"] or "", "td"), d.p(r["detail"], "small"),
                               d.p(money(r["debit"]) if r["debit"] else "", "num"),
                               d.p(money(r["credit"]) if r["credit"] else "", "num"),
                               d.p(money(r["balance"]), "num")]))
        data.append(d.row([d.p(date_to, "td"), d.p(t("Closing balance"), "h2"), d.p(""), d.p(""),
                           d.p(money(sec["debit"]), "numb"), d.p(money(sec["credit"]), "numb"),
                           d.p(money(sec["closing"]), "numb")]))
        story += [d.grid(data, d.widths(ws), total_rows=1), Spacer(1, 6 * mm)]
        # ageing
        from .statements import BUCKETS
        labels = [t(lbl) for _, lbl in BUCKETS] + [t("Unapplied"), t("Total")]
        vals = [sec["ageing"][k] for k, _ in BUCKETS] + [sec["unapplied"], sec["closing"]]
        age = [d.row([d.p(x, "thn") for x in labels]), d.row([d.p(money(v), "num") for v in vals])]
        story += [d.p(f"{t('Ageing')} ({cur})", "h2"), Spacer(1, 2 * mm),
                  d.grid(age, [180 * mm / 7] * 7, zebra=False), Spacer(1, 8 * mm)]
    story.append(d.p(t("Please contact us within 15 days if anything on this statement does not agree with your records."),
                     "small"))
    return d.build(story)


def invoice_pdf(company, inv, lines, branch, partner, decimals, residual):
    from .ledger import INVOICE_KINDS
    kind = INVOICE_KINDS[inv["kind"]]
    from .invoicetypes import title as doc_title
    title_en = doc_title(inv)[0]
    d = Doc(company, t(title_en), title_en)
    money = lambda v: fmt(v, decimals)  # noqa: E731
    info = [(t("Number"), inv["number"] or t("Draft")), (t("Date"), inv["date"])]
    if inv["due_date"]:
        info.append((t("Due Date"), inv["due_date"]))
    if inv["ref"]:
        info.append((t("Reference"), inv["ref"]))
    if inv["invoice_type"] == "debit_note" and inv["origin_id"]:
        from .db import q
        orig = q("SELECT number, date FROM invoices WHERE id = ?", (inv["origin_id"],), one=True)
        if orig:
            info.append((t("Original invoice"), f"{orig['number']} · {orig['date']}"))
        if inv["note_reason"]:
            info.append((t("Reason"), inv["note_reason"]))
    if inv["invoice_type"] == "proforma":
        info.append((t("Note"), t("This is not a tax invoice.")))
    story = d.header(info)
    who = [d.p(t("Bill to") if kind["partner_type"] == "customer" else t("Vendor"), "small"), d.p(nm(partner), "h2")]
    if partner["vat_no"]:
        who.append(d.p(d.kv(t("VAT"), partner["vat_no"]), "small"))
    if partner["address"]:
        who.append(d.p(partner["address"], "small"))
    br = [d.p(t("Branch"), "small"), d.p(nm(branch), "h2")]
    if branch["vat_no"]:
        br.append(d.p(d.kv(t("VAT"), branch["vat_no"]), "small"))
    blocks = Table([d.row([who, br])], colWidths=d.widths([110 * mm, 70 * mm]))
    blocks.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 0)]))
    story += [blocks, Spacer(1, 6 * mm)]
    ws = [8 * mm, 78 * mm, 20 * mm, 26 * mm, 20 * mm, 28 * mm]
    data = [d.row([d.p("#", "th"), d.p(t("Description"), "th"), d.p(t("Quantity"), "thn"), d.p(t("Unit Price"), "thn"),
                   d.p(t("VAT"), "thn"), d.p(t("Amount"), "thn")])]
    for i, ln in enumerate(lines, 1):
        desc = ln["description"] or ""
        if ln["pcode"]:
            desc = f"[{ln['pcode']}] {desc}"
        data.append(d.row([d.p(str(i)), d.p(desc), d.p(f"{ln['quantity']:g}", "num"), d.p(money(ln["price_unit"]), "num"),
                           d.p(f"{ln['trate']:g}%" if ln["trate"] is not None else "", "num"),
                           d.p(money(ln["subtotal"]), "num")]))
    story += [d.grid(data, d.widths(ws)), Spacer(1, 4 * mm)]
    totals = [(t("Untaxed Amount"), inv["amount_untaxed"], "num"), (t("VAT"), inv["amount_tax"], "num"),
              (f"{t('Total')} ({inv['currency'] or branch['currency']})", inv["amount_total"], "numb")]
    if inv["state"] == "posted" and residual != inv["amount_total"]:
        totals.append((t("Amount Due"), residual, "numb"))
    tdata = [d.row([d.p(lbl, "numb" if st == "numb" else "num"), d.p(money(v), st)]) for lbl, v, st in totals]
    tt = Table(tdata, colWidths=d.widths([45 * mm, 35 * mm]), hAlign="LEFT" if d.rtl else "RIGHT")
    tt.setStyle(TableStyle([("LINEABOVE", (0, 2), (-1, 2), 1, INK), ("TOPPADDING", (0, 0), (-1, -1), 3),
                            ("BOTTOMPADDING", (0, 0), (-1, -1), 3)]))
    story.append(tt)
    if inv["currency"]:
        story.append(d.p(f"1 {inv['currency']} = {inv['rate']} {branch['currency']}  ·  {t('VAT')} {branch['currency']} "
                         f"{fmt(int(round(inv['amount_tax'] * inv['rate'])), 2)}", "small"))
    if inv["notes"]:
        story += [Spacer(1, 6 * mm), d.p(t("Notes"), "small"), d.p(inv["notes"])]
    if inv["terms"]:
        story += [Spacer(1, 6 * mm), d.p(t("Terms & Conditions"), "h2"), d.p(inv["terms"], "small")]
    story.append(d.signatures())
    return d.build(story)
