# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import UserError
from markupsafe import Markup


class ModAwaitingFundingWizard(models.TransientModel):
    _name = 'fusion_claims.mod.awaiting.funding.wizard'
    _description = 'MOD - Record Application Submission'

    sale_order_id = fields.Many2one('sale.order', required=True, readonly=True)
    application_submitted_date = fields.Date(
        string='Application Submitted Date',
        required=True,
        default=fields.Date.context_today,
        help='Date the application/proposal was submitted to March of Dimes',
    )
    notes = fields.Text(string='Notes', help='Optional notes about the submission')

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        if self.env.context.get('active_id'):
            order = self.env['sale.order'].browse(self.env.context['active_id'])
            res['sale_order_id'] = order.id
            if order.x_fc_mod_application_submitted_date:
                res['application_submitted_date'] = order.x_fc_mod_application_submitted_date
        return res

    def action_confirm(self):
        self.ensure_one()
        order = self.sale_order_id
        order.write({
            'x_fc_mod_status': 'awaiting_funding',
            'x_fc_mod_application_submitted_date': self.application_submitted_date,
        })
        # Log to chatter
        date_str = self.application_submitted_date.strftime('%B %d, %Y')
        note_html = (
            f'<strong>Application submitted to March of Dimes</strong> on {date_str}'
        )
        if self.notes:
            note_html += f'<br/>{self.notes}'
        order.message_post(
            body=Markup(
                f'<div class="alert alert-info" role="alert">'
                f'{note_html}</div>'
            ),
            message_type='notification',
            subtype_xmlid='mail.mt_note',
        )
        return {'type': 'ir.actions.act_window_close'}
