from markupsafe import Markup

from odoo import _, api, fields, models
from odoo.exceptions import ValidationError

_STATUS = [
    ("planned", "Planned"),
    ("ongoing", "Ongoing"),
    ("completed", "Completed"),
    ("cancelled", "Cancelled"),
]


class XenoHrActivity(models.Model):
    """Company-hosted events/activities (guest visits, town halls, team
    events) -- named xeno.hr.activity, distinct from core's own
    mail.activity (a completely unrelated "to-do reminder" concept).

    History Timeline: Community has no Enterprise Gantt/timeline widget
    (same constraint noted for the Leave Balance grid -- see
    xeno_leave_balance_grid), so "timeline view of past and upcoming
    activities" is delivered as a Calendar view (date_from/date_to) plus a
    date-sorted List view with Upcoming/Past search filters -- both
    Community-native.
    """

    _name = "xeno.hr.activity"
    _description = "Company Activity"
    _inherit = ["mail.thread"]
    _order = "date_from desc, id desc"

    name = fields.Char(required=True, tracking=True)
    description = fields.Html(default="<p></p>")
    date_from = fields.Date(string="Start Date", default=fields.Date.context_today,
                             required=True, tracking=True)
    date_to = fields.Date(string="End Date", required=True, tracking=True)
    location = fields.Char(tracking=True)
    host_id = fields.Many2one("hr.employee", string="Host / Owner", tracking=True)
    status = fields.Selection(_STATUS, default="planned", required=True, tracking=True)
    active = fields.Boolean(default=True, tracking=True)

    is_leave_restricted = fields.Boolean(
        string="Restrict Leave on These Dates", default=False, tracking=True,
        help="When enabled, employees cannot self-service a leave request "
             "that overlaps this activity's Start/End Date (e.g. a Guest "
             "Visit day) -- see the 'No leave on restricted activity days' "
             "rule on the Leave Validations page. A genuine emergency is "
             "not an in-system override: the employee must contact HR "
             "directly.")

    @api.constrains("date_from", "date_to")
    def _check_dates(self):
        for rec in self:
            if rec.date_from and rec.date_to and rec.date_to < rec.date_from:
                raise ValidationError(_("End date cannot be before start date."))

    @api.onchange("date_from")
    def _onchange_date_from(self):
        for rec in self:
            if rec.date_from and (not rec.date_to or rec.date_to < rec.date_from):
                rec.date_to = rec.date_from

    def action_create_announcement(self):
        """Opens a new Announcement pre-filled from this activity (title,
        dates, description) -- HR still picks Target Audience and Send
        Email Notification themselves, nothing auto-sends. Mirrors
        xeno.hr.policy's own action_create_announcement exactly."""
        self.ensure_one()
        return {
            "type": "ir.actions.act_window",
            "res_model": "xeno.hr.announcement",
            "views": [[False, "form"]],
            "target": "new",
            "context": {
                "default_name": self.name,
                "default_body": self.description,
                "default_start_date": self.date_from,
                "default_end_date": self.date_to,
                "default_source_activity_id": self.id,
            },
        }

    def _xeno_log_announcement_created(self, announcement):
        self.ensure_one()
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        action_id = self.env.ref("xeno_theme_slate.action_xeno_hr_announcement").id
        url = "%s/odoo/action-%s/%s" % (base_url, action_id, announcement.id)
        template = Markup(_('Announcement created from this activity: <a href="%s">%s</a>'))
        self.message_post(body=template % (url, announcement.name))
