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

from odoo import api, fields, models, _
import logging

_logger = logging.getLogger(__name__)

STATUS_DOMAINS = {
    'all': [],
    'sent': [('state', '=', 'sent')],
    'failed': [('state', '=', 'failed')],
    'draft': [('state', '=', 'draft')],
    'received': [('state', '=', 'received')],
}


class FusionFaxDashboard(models.TransientModel):
    _name = 'fusion.fax.dashboard'
    _description = 'Fusion Fax Dashboard'
    _rec_name = 'name'

    name = fields.Char(default='Fax Dashboard', readonly=True)

    # KPI stat fields
    total_count = fields.Integer(compute='_compute_stats')
    sent_count = fields.Integer(compute='_compute_stats')
    received_count = fields.Integer(compute='_compute_stats')
    failed_count = fields.Integer(compute='_compute_stats')
    draft_count = fields.Integer(compute='_compute_stats')

    # Recent faxes as a proper relational field for embedded list
    recent_fax_ids = fields.Many2many(
        'fusion.fax',
        compute='_compute_recent_faxes',
    )

    def _compute_stats(self):
        Fax = self.env['fusion.fax'].sudo()
        for rec in self:
            rec.total_count = Fax.search_count([])
            rec.sent_count = Fax.search_count(STATUS_DOMAINS['sent'])
            rec.received_count = Fax.search_count(STATUS_DOMAINS['received'])
            rec.failed_count = Fax.search_count(STATUS_DOMAINS['failed'])
            rec.draft_count = Fax.search_count(STATUS_DOMAINS['draft'])

    def _compute_recent_faxes(self):
        Fax = self.env['fusion.fax'].sudo()
        for rec in self:
            rec.recent_fax_ids = Fax.search([], order='create_date desc', limit=20)

    # ------------------------------------------------------------------
    # Actions
    # ------------------------------------------------------------------

    def action_open_all(self):
        return self._open_fax_list('All Faxes', STATUS_DOMAINS['all'])

    def action_open_sent(self):
        return self._open_fax_list('Sent Faxes', STATUS_DOMAINS['sent'])

    def action_open_received(self):
        return self._open_fax_list('Received Faxes', STATUS_DOMAINS['received'])

    def action_open_failed(self):
        return self._open_fax_list('Failed Faxes', STATUS_DOMAINS['failed'])

    def action_open_draft(self):
        return self._open_fax_list('Draft Faxes', STATUS_DOMAINS['draft'])

    def _open_fax_list(self, name, domain):
        return {
            'type': 'ir.actions.act_window',
            'name': name,
            'res_model': 'fusion.fax',
            'view_mode': 'list,form',
            'domain': domain,
        }

    def action_send_fax(self):
        return {
            'type': 'ir.actions.act_window',
            'name': 'Send Fax',
            'res_model': 'fusion_faxes.send.fax.wizard',
            'view_mode': 'form',
            'target': 'new',
        }
