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

_logger = logging.getLogger(__name__)


class ModFundingApprovedWizard(models.TransientModel):
    _name = 'fusion_claims.mod.funding.approved.wizard'
    _description = 'MOD - Record Funding Approval'

    sale_order_id = fields.Many2one('sale.order', required=True, readonly=True)

    # Case details
    case_worker_id = fields.Many2one(
        'res.partner', string='Case Worker',
        help='March of Dimes case worker assigned to this case',
    )
    hvmp_reference = fields.Char(string='HVMP Reference #')

    @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_case_worker:
                res['case_worker_id'] = order.x_fc_case_worker.id
            if order.x_fc_case_reference:
                res['hvmp_reference'] = order.x_fc_case_reference
        return res

    def action_confirm(self):
        """Record funding approval - just case worker and reference."""
        self.ensure_one()
        order = self.sale_order_id

        vals = {
            'x_fc_mod_status': 'funding_approved',
            'x_fc_case_approved': fields.Date.today(),
        }
        if self.case_worker_id:
            vals['x_fc_case_worker'] = self.case_worker_id.id
        if self.hvmp_reference:
            vals['x_fc_case_reference'] = self.hvmp_reference
        order.write(vals)

        # Log to chatter
        parts = ['<strong>Funding Approved by March of Dimes</strong>']
        parts.append(f'Date: {fields.Date.today().strftime("%B %d, %Y")}')
        if self.case_worker_id:
            parts.append(f'Case Worker: {self.case_worker_id.name}')
        if self.hvmp_reference:
            parts.append(f'HVMP Reference: {self.hvmp_reference}')

        order.message_post(
            body=Markup('<div class="alert alert-success">' + '<br/>'.join(parts) + '</div>'),
            message_type='notification', subtype_xmlid='mail.mt_note',
        )
        return {'type': 'ir.actions.act_window_close'}


class ModFundingApprovedWizardLine(models.TransientModel):
    _name = 'fusion_claims.mod.funding.approved.wizard.line'
    _description = 'MOD PCA - Line Preview'

    wizard_id = fields.Many2one('fusion_claims.mod.pca.received.wizard', ondelete='cascade')
    product_name = fields.Char(string='Product', readonly=True)
    quantity = fields.Float(string='Qty', readonly=True)
    line_total = fields.Float(string='Line Total', readonly=True)
    mod_amount = fields.Float(string='MOD Pays', readonly=True)
    client_amount = fields.Float(string='Client Pays', readonly=True)
