import uuid

from odoo import _, api, fields, models


class RentalCancellationRequest(models.Model):
    _name = 'rental.cancellation.request'
    _description = 'Rental Cancellation Request'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'request_date desc'
    _rec_name = 'display_name'

    order_id = fields.Many2one(
        'sale.order',
        string="Rental Order",
        required=True,
        ondelete='cascade',
        index=True,
    )
    partner_id = fields.Many2one(
        related='order_id.partner_id',
        store=True,
        string="Customer",
    )
    request_date = fields.Datetime(
        string="Request Date",
        default=fields.Datetime.now,
    )
    requested_pickup_date = fields.Datetime(string="Requested Pickup Date")
    reason = fields.Text(string="Reason")
    state = fields.Selection(
        [
            ('new', 'New'),
            ('confirmed', 'Confirmed'),
            ('pickup_scheduled', 'Pickup Scheduled'),
            ('completed', 'Completed'),
            ('rejected', 'Rejected'),
        ],
        string="Status",
        default='new',
        required=True,
        tracking=True,
    )
    assigned_user_id = fields.Many2one(
        'res.users',
        string="Assigned To",
        tracking=True,
    )
    pickup_activity_id = fields.Many2one(
        'mail.activity',
        string="Pickup Activity",
        ondelete='set null',
    )
    token = fields.Char(
        string="Security Token",
        default=lambda self: uuid.uuid4().hex,
        copy=False,
        index=True,
    )

    def _compute_display_name(self):
        for rec in self:
            rec.display_name = (
                f"{rec.order_id.name or 'New'} - {rec.partner_id.name or 'Customer'}"
            )

    def action_confirm(self):
        """Confirm the cancellation and stop auto-renewal."""
        self.ensure_one()
        self.order_id.write({
            'rental_auto_renew': False,
            'rental_auto_renew_off_reason': f"Customer requested cancellation ({self.reason or 'No reason provided'})",
        })
        self.write({'state': 'confirmed'})
        self._schedule_pickup_activity()
        self._send_cancellation_confirmation()

    def action_schedule_pickup(self):
        """Mark pickup as scheduled."""
        self.ensure_one()
        self.write({'state': 'pickup_scheduled'})

    def action_complete(self):
        """Mark the cancellation and pickup as completed."""
        self.ensure_one()
        self.write({'state': 'completed'})
        if self.pickup_activity_id and not self.pickup_activity_id.date_done:
            self.pickup_activity_id.action_done()

    def action_reject(self):
        """Reject the cancellation request."""
        self.ensure_one()
        self.write({'state': 'rejected'})

    def _schedule_pickup_activity(self):
        """Create a to-do activity on the sale order for staff to schedule pickup."""
        self.ensure_one()
        assigned_user = (
            self.assigned_user_id
            or self.order_id.user_id
            or self.env.user
        )
        activity = self.order_id.activity_schedule(
            'mail.mail_activity_data_todo',
            date_deadline=fields.Date.today(),
            summary=_(
                "Schedule rental pickup for %s",
                self.partner_id.name or self.order_id.partner_id.name,
            ),
            note=_(
                "Customer has requested cancellation and pickup for rental %s. "
                "Please contact them to schedule a pickup.",
                self.order_id.name,
            ),
            user_id=assigned_user.id,
        )
        self.pickup_activity_id = activity

    def _send_cancellation_confirmation(self):
        """Send confirmation email to the customer."""
        template = self.env.ref(
            'fusion_rental.mail_template_rental_cancellation_confirmed',
            raise_if_not_found=False,
        )
        if template:
            template.send_mail(self.order_id.id, force_send=True)
