from odoo import _, api, models
from odoo.tools import html_escape

# Same branded-HTML-shell idiom as xeno_overtime's overtime_email.py, minus
# the HMAC one-click approve/reject action links -- these are informational
# notifications with a plain "See More" link back to the record (a full
# email-driven approve/reject flow across 4 roles and 9 notification
# points is a meaningfully larger, separate feature; flagged as a
# reasonable v2 add-on rather than built here).
_HEADER = """
<div style="max-width:600px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:#142933;border:1px solid #d8e1e4;">
  <div style="background:#142933;padding:14px 20px;">
    <div style="color:#fff;">
      <div style="font-weight:700;font-size:16px;">XenOptics HR System</div>
      <div style="font-size:12px;color:#b7c7cc;">Outside Request &amp; Reimbursement</div>
    </div>
  </div>
  <div style="padding:20px;">
    <div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:10px;">
      <h2 style="margin:0;font-size:20px;">%(title)s</h2>
      <a href="%(see_more)s" style="background:#ec1d23;color:#fff;padding:5px 12px;border-radius:14px;font-size:11px;text-decoration:none;">See More</a>
    </div>
    %(rows)s
"""

_FOOTER = """
  </div>
  <div style="background:#142933;color:#b7c7cc;text-align:center;padding:8px;font-size:11px;">
    XenOptics HR &middot; Do not reply
  </div>
</div>
"""


def _esc(value):
    return html_escape(value if value is not None else "")


def _row(label, value):
    return '<div style="margin:6px 0;font-size:13px;"><strong>%s:</strong> %s</div>' % (label, value)


class XenoOrrRequest(models.Model):
    _inherit = "xeno.orr.request"

    def _xeno_see_more_url(self):
        self.ensure_one()
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        action_id = self.env.ref("xeno_orr.action_xeno_orr_request").id
        return "%s/odoo/action-%s/%s" % (base_url, action_id, self.id)

    def _xeno_request_email_rows(self):
        self.ensure_one()
        R = self.sudo()
        rows = [
            _row("Requestor", _esc(R.employee_id.name)),
            _row("Supervisor", _esc(R.supervisor_id.name)),
            _row("Date &amp; Time Leaving", _esc(str(R.datetime_leaving or ""))),
            _row("Vehicle", _esc(dict(self._fields["vehicle_type"].selection).get(R.vehicle_type, "-"))),
            _row("Places", _esc(", ".join(R.stop_ids.mapped("place")) or "-")),
        ]
        if R.outside_reject_reason:
            rows.append(_row("Reject Reason", _esc(R.outside_reject_reason)))
        return "".join(rows)

    def _xeno_send_mail(self, email_to, subject, title):
        self.ensure_one()
        if not email_to:
            return
        body = (_HEADER % {
            "title": _esc(title),
            "see_more": self._xeno_see_more_url(),
            "rows": self._xeno_request_email_rows(),
        }) + _FOOTER
        self.env["mail.mail"].sudo().create({
            "subject": subject,
            "body_html": body,
            "email_to": email_to,
            "auto_delete": True,
        }).send()

    def _xeno_employee_email(self, employee):
        return employee.work_email or (employee.user_id.email if employee.user_id else False)

    def _xeno_notify_outside_submitted(self):
        for rec in self:
            rec._xeno_send_mail(
                rec._xeno_employee_email(rec.employee_id),
                _("Outside Request Submitted – %s", rec.name),
                _("Your Outside Request has been submitted"))

    def _xeno_notify_outside_approved(self):
        for rec in self:
            rec._xeno_send_mail(
                rec._xeno_employee_email(rec.employee_id),
                _("Outside Request Approved – %s", rec.name),
                _("Your Outside Request was approved. You can now ask for reimbursement."))


class XenoOrrReimbursement(models.Model):
    _inherit = "xeno.orr.reimbursement"

    def _xeno_see_more_url(self):
        self.ensure_one()
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        action_id = self.env.ref("xeno_orr.action_xeno_orr_reimbursement").id
        return "%s/odoo/action-%s/%s" % (base_url, action_id, self.id)

    def _xeno_reimbursement_email_rows(self):
        self.ensure_one()
        R = self.sudo()
        rows = [
            _row("Requestor", _esc(R.employee_id.name)),
            _row("Attempt", _esc(str(R.attempt_number))),
            _row("Type", _esc(dict(self._fields["reimbursement_type"].selection).get(R.reimbursement_type, "-"))),
            _row("Amount", _esc("%.2f" % R.total_amount)),
        ]
        if R.reject_reason:
            rows.append(_row("Reject Reason", _esc(R.reject_reason)))
        return "".join(rows)

    def _xeno_send_mail(self, email_to, subject, title):
        self.ensure_one()
        if not email_to:
            return
        body = (_HEADER % {
            "title": _esc(title),
            "see_more": self._xeno_see_more_url(),
            "rows": self._xeno_reimbursement_email_rows(),
        }) + _FOOTER
        self.env["mail.mail"].sudo().create({
            "subject": subject,
            "body_html": body,
            "email_to": email_to,
            "auto_delete": True,
        }).send()

    def _xeno_employee_email(self, employee):
        return employee.work_email or (employee.user_id.email if employee.user_id else False)

    def _xeno_group_emails(self, xmlid):
        users = self.env.ref(xmlid).users
        return [u.email for u in users if u.email]

    def _xeno_notify_reimbursement_submitted(self):
        for rec in self:
            supervisor = rec.request_id.supervisor_id
            rec._xeno_send_mail(
                rec._xeno_employee_email(supervisor),
                _("Reimbursement Requested – %s", rec.request_id.name),
                _("A reimbursement request is awaiting your approval"))

    def _xeno_notify_reimbursement_supervisor_approved(self):
        for rec in self:
            supervisor = rec.request_id.supervisor_id
            rec._xeno_send_mail(
                rec._xeno_employee_email(supervisor),
                _("Reimbursement Approved – %s", rec.request_id.name),
                _("You approved this reimbursement request"))
            for email in rec._xeno_group_emails("xeno_orr.group_orr_management"):
                rec._xeno_send_mail(email, _("New Reimbursement for Management – %s", rec.request_id.name),
                                     _("A reimbursement is awaiting Management approval"))

    def _xeno_notify_reimbursement_supervisor_rejected(self):
        for rec in self:
            supervisor = rec.request_id.supervisor_id
            rec._xeno_send_mail(
                rec._xeno_employee_email(supervisor),
                _("Reimbursement Rejected – %s", rec.request_id.name),
                _("You rejected this reimbursement request"))
            rec._xeno_send_mail(
                rec._xeno_employee_email(rec.request_id.employee_id),
                _("Reimbursement Rejected – %s", rec.request_id.name),
                _("Your reimbursement was rejected by your Supervisor. You can resend it."))

    def _xeno_notify_reimbursement_management_decided(self, approved):
        for rec in self:
            title = _("Reimbursement approved by Management") if approved else _("Reimbursement rejected by Management")
            for email in rec._xeno_group_emails("xeno_orr.group_orr_management"):
                rec._xeno_send_mail(
                    email,
                    _("Reimbursement %(status)s – %(name)s",
                      status=_("Approved") if approved else _("Rejected"), name=rec.request_id.name),
                    title)

    def _xeno_notify_reimbursement_completed(self):
        for rec in self:
            rec._xeno_send_mail(
                rec._xeno_employee_email(rec.request_id.employee_id),
                _("Reimbursement Completed – %s", rec.request_id.name),
                _("Your reimbursement has been completed by Finance"))

    def _xeno_notify_ask_back(self, amount, reason):
        for rec in self:
            rec._xeno_send_mail(
                rec._xeno_employee_email(rec.request_id.employee_id),
                _("Ask Back Requested – %s", rec.request_id.name),
                _("Management has requested %(amount).2f back: %(reason)s", amount=amount, reason=reason))
