from datetime import date

from flask import Blueprint, abort, flash, redirect, render_template, request, url_for

from .. import check_branch, context_branch_ids, login_required, module_required, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, now
from ..money import to_int
from ..schedules import KINDS, confirm_schedule, post_recognitions, recognition_lines
from ..stock import next_number
from ..attachments import remove_all as remove_attachments
from ..costcentres import options as cost_centre_options, parse as parse_cost_centre
from .common import accounts_list, branch_map, default_branch, partners_list, user_id

bp = Blueprint("prepaid", __name__, url_prefix="/prepaid")
bp.before_request(module_required("prepaid"))
DEFAULT_BALANCE = {"prepaid": "1300", "deferred": "2600", "accrual": "2300"}


def get_schedule(sid):
    s = q("SELECT s.*, p.name_en AS pname_en, p.name_ar AS pname_ar, ba.code AS bcode, ba.name_en AS bname_en, "
          "ba.name_ar AS bname_ar, pa.code AS pcode, pa.name_en AS plname_en, pa.name_ar AS plname_ar, "
          "i.number AS inv_number FROM prepaid_schedules s LEFT JOIN partners p ON p.id = s.partner_id "
          "JOIN accounts ba ON ba.id = s.balance_account_id JOIN accounts pa ON pa.id = s.pl_account_id "
          "LEFT JOIN invoices i ON i.id = s.invoice_id WHERE s.id = ?", (sid,), one=True)
    if not s:
        abort(404)
    check_branch(s["branch_id"])
    return s


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    kind = request.args.get("kind", "")
    rows = []
    if ids:
        sql = (f"SELECT s.*, p.name_en AS pname_en, p.name_ar AS pname_ar, "
               f"COALESCE((SELECT SUM(amount) FROM prepaid_lines WHERE schedule_id = s.id AND move_id IS NOT NULL), 0) AS recognized "
               f"FROM prepaid_schedules s LEFT JOIN partners p ON p.id = s.partner_id WHERE s.branch_id IN ({placeholders(ids)})")
        args = list(ids)
        if kind in KINDS:
            sql += " AND s.kind = ?"
            args.append(kind)
        rows = q(sql + " ORDER BY s.start_date DESC, s.id DESC", args)
    return render_template("prepaid/list.html", rows=rows, kind=kind, kinds=KINDS, branches=branch_map())


@bp.route("/new", methods=["GET", "POST"])
@bp.route("/<int:sid>/edit", methods=["GET", "POST"])
@write_required
def form(sid=None):
    s = get_schedule(sid) if sid else None
    if s and s["state"] != "draft":
        flash(t("Only draft documents can be edited."), "error")
        return redirect(url_for("prepaid.view", sid=sid))
    kind = (s["kind"] if s else request.values.get("kind")) or "prepaid"
    if kind not in KINDS:
        abort(404)
    if request.method == "POST":
        f = request.form
        try:
            branch_id = check_branch(f["branch_id"])
            vals = {"kind": kind, "name": f["name"].strip(), "branch_id": branch_id,
                    "partner_id": int(f["partner_id"]) if f.get("partner_id") else None,
                    "invoice_id": int(f["invoice_id"]) if f.get("invoice_id") else None,
                    "balance_account_id": int(f["balance_account_id"]), "pl_account_id": int(f["pl_account_id"]),
                    "total": to_int(f["total"]), "start_date": f["start_date"], "months": int(f["months"]),
                    "auto_reverse": 1 if f.get("auto_reverse") else 0, "notes": f.get("notes"),
                    "cost_centre_id": parse_cost_centre(f.get("cost_centre_id"))}
            if not vals["name"]:
                raise AccountingError(t("Name (English)") + ": " + t("is required"))
            if vals["total"] <= 0 or vals["months"] <= 0:
                raise AccountingError(t("The amount must be greater than zero."))
            if s:
                x(f"UPDATE prepaid_schedules SET {', '.join(k + ' = ?' for k in vals)} WHERE id = ?",
                  list(vals.values()) + [sid])
            else:
                prefix = {"prepaid": "PPD", "deferred": "DEF", "accrual": "ACR"}[kind]
                vals.update(number=next_number("prepaid_schedules", "number", prefix, branch_id, vals["start_date"]),
                            state="draft", created_by=user_id(), created_at=now())
                sid = x(f"INSERT INTO prepaid_schedules ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})",
                        list(vals.values()))
            if f.get("action") == "confirm":
                confirm_schedule(sid, user_id())
            audit(user_id(), "save", "prepaid", sid)
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("prepaid.view", sid=sid))
        except (AccountingError, ValueError, KeyError) as e:
            get_db().rollback()
            flash(str(e), "error")
            s = dict(request.form.items())
            s["kind"] = kind
    elif not s:
        # prefill from a vendor bill / customer invoice
        inv_id = request.args.get("invoice_id", type=int)
        s = {"kind": kind, "branch_id": default_branch(), "start_date": date.today().isoformat(), "months": 12}
        bal = q("SELECT id FROM accounts WHERE code = ?", (DEFAULT_BALANCE[kind],), one=True)
        s["balance_account_id"] = bal["id"] if bal else None
        if inv_id:
            inv = q("SELECT * FROM invoices WHERE id = ?", (inv_id,), one=True)
            if inv:
                check_branch(inv["branch_id"])
                s.update(branch_id=inv["branch_id"], partner_id=inv["partner_id"], invoice_id=inv["id"],
                         total=inv["amount_untaxed"], start_date=inv["date"], name=f"{inv['number']} {inv['ref'] or ''}".strip())
    return render_template("prepaid/form.html", s=s, kind=kind, info=KINDS[kind], branches=branch_map(),
                           accounts=accounts_list(), partners=partners_list(), default_branch=default_branch(),
                           cost_centres=cost_centre_options(dict(s).get("cost_centre_id") if s else None))


@bp.route("/<int:sid>")
@login_required
def view(sid):
    s = get_schedule(sid)
    lines = q("SELECT * FROM prepaid_lines WHERE schedule_id = ? ORDER BY date", (sid,))
    preview = []
    branch = q("SELECT * FROM branches WHERE id = ?", (s["branch_id"],), one=True)
    if s["state"] == "draft":
        from ..schedules import branch_decimals
        preview = recognition_lines(s["total"], s["start_date"], s["months"], branch_decimals(s["branch_id"]))
    recognized = sum(ln["amount"] for ln in lines if ln["move_id"])
    return render_template("prepaid/view.html", s=s, lines=lines, preview=preview, info=KINDS[s["kind"]],
                           recognized=recognized, branch=branch, today=date.today().isoformat())


@bp.route("/<int:sid>/<action>", methods=["POST"])
@write_required
def action(sid, action):
    s = get_schedule(sid)
    try:
        if action == "confirm":
            confirm_schedule(sid, user_id())
        elif action == "post":
            n, r = post_recognitions(request.form.get("date") or date.today().isoformat(), [s["branch_id"]], user_id(), sid)
            flash(f"{n} {t('entries posted')}, {r} {t('reversals')}", "success")
        elif action == "cancel" and s["state"] in ("draft", "running"):
            if q("SELECT 1 FROM prepaid_lines WHERE schedule_id = ? AND move_id IS NOT NULL", (sid,)):
                raise AccountingError(t("Entries are already posted for this schedule."))
            x("DELETE FROM prepaid_lines WHERE schedule_id = ?", (sid,))
            x("UPDATE prepaid_schedules SET state = 'cancelled' WHERE id = ?", (sid,))
        elif action == "draft" and s["state"] == "cancelled":
            x("UPDATE prepaid_schedules SET state = 'draft' WHERE id = ?", (sid,))
        elif action == "delete" and s["state"] in ("draft", "cancelled"):
            x("DELETE FROM prepaid_schedules WHERE id = ?", (sid,))
            remove_attachments("prepaid", sid)
            commit()
            return redirect(url_for("prepaid.index"))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        audit(user_id(), action, "prepaid", sid, s["number"])
        commit()
        if action != "post":
            flash(t("Done."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("prepaid.view", sid=sid))
