# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

from datetime import timedelta

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


class SendPage11Wizard(models.TransientModel):
    _name = 'fusion_claims.send.page11.wizard'
    _description = 'Send Page 11 for Remote Signing'

    sale_order_id = fields.Many2one(
        'sale.order', string='Sale Order',
        required=True, readonly=True,
    )
    signer_email = fields.Char(string='Recipient Email', required=True)
    signer_type = fields.Selection([
        ('client', 'Client (Self)'),
        ('spouse', 'Spouse'),
        ('parent', 'Parent'),
        ('legal_guardian', 'Legal Guardian'),
        ('poa', 'Power of Attorney'),
        ('public_trustee', 'Public Trustee'),
    ], string='Signer Type', default='client', required=True)
    signer_name = fields.Char(string='Signer Name', required=True)
    custom_message = fields.Text(
        string='Personal Message',
        help='Optional message to include in the signing request email.',
    )
    expiry_days = fields.Integer(
        string='Link Valid For (days)', default=7, required=True,
    )

    client_name = fields.Char(string='Client', readonly=True)
    case_ref = fields.Char(string='Case Reference', readonly=True)

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        active_id = self.env.context.get('active_id')
        if not active_id:
            return res

        order = self.env['sale.order'].browse(active_id)
        res['sale_order_id'] = order.id
        res['client_name'] = order.partner_id.name or ''
        res['case_ref'] = order.name or ''
        res['signer_name'] = order.partner_id.name or ''
        res['signer_email'] = order.partner_id.email or ''
        return res

    def action_send(self):
        """Create a signing request and send the email."""
        self.ensure_one()

        if not self.signer_email:
            raise UserError(_("Please enter the recipient's email address."))
        if self.expiry_days < 1:
            raise UserError(_("Expiry must be at least 1 day."))

        request = self.env['fusion.page11.sign.request'].create({
            'sale_order_id': self.sale_order_id.id,
            'signer_email': self.signer_email,
            'signer_type': self.signer_type,
            'signer_name': self.signer_name,
            'custom_message': self.custom_message,
            'expiry_date': fields.Datetime.now() + timedelta(days=self.expiry_days),
            'consent_signed_by': 'applicant' if self.signer_type == 'client' else 'agent',
            'signer_relationship': dict(self._fields['signer_type'].selection).get(
                self.signer_type, ''
            ) if self.signer_type != 'client' else '',
        })

        request._send_signing_email()

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Page 11 Signing Request Sent'),
                'message': _(
                    'Signing request has been sent to %s.',
                    self.signer_email,
                ),
                'type': 'success',
                'sticky': False,
                'next': {'type': 'ir.actions.act_window_close'},
            },
        }
