# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from datetime import date
from odoo.exceptions import UserError, ValidationError


class ReasearcherMemberWizard(models.TransientModel):
    _name = 'researcher.member.wizard'

    def _default_member(self):
        return self._context.get('active_id')

    # selector = fields.Selection([
    #     ('researcher', 'Researcher'),
    #     ('researcher_team', 'Researcher Team'),
    # ], string='Selector' ,default="researcher")
    # researcher_id = fields.Many2one("hr.employee", string="Researcher")
    researcher_team = fields.Many2one("committees.line", string="Researcher Team")
    member_id = fields.Many2one("family.member", string="Member", default=_default_member)

    def submit_member(self):
        for rec in self:
            rec.member_id.state_a = "complete_info"
            # rec.member.researcher_id = rec.researcher_team.id
            # self.env['visit.location'].create({
            #     'benefit_id': rec._id.id,
            #     'visit_date': date.today(),
            #     'visit_types': 1,
            #     'contact_type': 'email',
            #     # 'selector': rec.selector,
            #     # 'researcher_id': rec.researcher_id.id,
            #     'researcher_team': rec.researcher_team.id,
            #     'state': 'draft'
            # })


class ReasearcherFamilyWizard(models.TransientModel):
    _name = 'researcher.family.wizard'

    def _default_benefit_ids(self):
        active_ids = self._context.get('active_ids', [])
        if active_ids:
            return [(6, 0, active_ids)]
        return False

    def _default_branch_custom_id(self):
        active_ids = self._context.get('active_ids', [])
        if active_ids:
            benefit = self.env['grant.benefit'].browse(active_ids[0])
            return benefit.branch_custom_id.id
        return False

    researcher_team = fields.Many2one("committees.line", string="Researcher Team", )
    benefit_ids = fields.Many2many('grant.benefit', string='Families', default=_default_benefit_ids, required=True)
    branch_custom_id = fields.Many2one("branch.settings", string="Branch",
                                       domain="[('has_employees', '=', True)]",
                                       default=_default_branch_custom_id)
    branch_has_employees = fields.Boolean(string='Has Employees In Branch', compute='_compute_branch_has_employees',
                                          store=False)
    is_submitted = fields.Boolean(string="Submitted", default=False)
    assignment_type = fields.Selection([
        ('researcher', 'Assign Researcher'),
        ('assigned_researcher', 'Assign Assigned Researcher'),
        ('end_assignment', 'End Assignment'),
    ], string='Assignment Type', default='researcher')

    @api.depends('benefit_ids')
    def _compute_branch_has_employees(self):
        for wizard in self:
            if wizard.benefit_ids:
                wizard.branch_has_employees = wizard.benefit_ids[0].branch_has_employees
            else:
                wizard.branch_has_employees = False

    @api.onchange('benefit_ids')
    def _onchange_benefit_ids(self):
        if self.benefit_ids:
            branches = self.benefit_ids.mapped('branch_custom_id')
            if len(branches) > 1:
                raise ValidationError(_('All selected families must be from the same branch'))
            if branches:
                self.branch_custom_id = branches[0].id

    def submit_family(self):
        if not self.benefit_ids:
            raise ValidationError(_('Please select at least one family'))
        branches = self.benefit_ids.mapped('branch_custom_id')
        if len(branches) > 1:
            raise ValidationError(_('All selected families must be from the same branch'))
        draft_records = self.benefit_ids.filtered(lambda b: b.state == 'draft')
        if draft_records:
            raise ValidationError(
                _('You cannot assign a researcher while one or more files are in Draft state.')
            )
        create_visit = self.env.context.get('create_visit', False)

        for benefit in self.benefit_ids:
            update_vals = {}
            if create_visit:
                update_vals = {
                    'state': 'complete_info',
                    'contact_type': 'sms',
                    'branch_custom_id': self.branch_custom_id.id,
                }
            if self.assignment_type == 'researcher':
                update_vals['researcher_id'] = self.researcher_team.id
            elif self.assignment_type == 'assigned_researcher':
                update_vals['assigned_researcher_id'] = self.researcher_team.id
            elif self.assignment_type == 'end_assignment':
                update_vals['assigned_researcher_id'] = False
            benefit.with_context(bypass_attachments_requirement=True).write(update_vals)

            specialist_name = self.researcher_team.name or _('Not Specified')
            if create_visit:
                visit_record = self.env['visit.location'].create({
                    'benefit_id': benefit.id,
                    'visit_date': date.today(),
                    'visit_types': 1,
                    'researcher_team': self.researcher_team.id,
                    'state': 'draft'
                })
                self._send_assignment_notification(visit_record)
                visit_number = visit_record.name or str(visit_record.id)
                message = _('File has been assigned to specialist "%s" and initial visit created with number "%s"') % (
                    specialist_name, visit_number)
                return {
                    'type': 'ir.actions.client',
                    'tag': 'display_notification',
                    'params': {
                        'title': _('Assignment Successful ✓'),
                        'message': message,
                        'type': 'success',
                        'sticky': False,
                        'next': {
                            'type': 'ir.actions.act_window_close'
                        }
                    }
                }

        self.is_submitted = True

    def action_return_to_benefit(self):
        return {
            'type': 'ir.actions.act_window_close',
            'flags': {'search_view': True}
        }

    def send_visit_date_email(self):
        template = self.env.ref('odex_benefit.visit_date_email', False)
        if not template:
            return
        template.with_context(lang=self.env.user.lang).send_mail(self.id, force_send=True, raise_exception=False)

    def _send_assignment_notification(self, visit_record=None):
        if not self.researcher_team or not self.researcher_team.employee_id:
            return
        for employee in self.researcher_team.employee_id:
            user = employee.user_id
            if not user or not user.active:
                continue

            notification_type = getattr(user, 'notification_type', 'email')
            if notification_type == 'email':
                self._send_email_notification(user, visit_record)
            else:
                self._send_in_system_notification(user, visit_record)

    def _send_email_notification(self, specialist_user, visit_record):
        try:
            template = self.env.ref('odex_benefit.visit_notification_template', False)
            if not template:
                return
            template.write({
                'email_to': specialist_user.work_email or specialist_user.email,
                'email_cc': self.env.user.company_id.hr_email or self.env.user.company_id.email,
            })
            template.with_context(lang=self.env.user.lang).send_mail(visit_record.id, force_send=True,
                                                                     raise_exception=False)

        except Exception as e:
            self._send_in_system_notification(specialist_user, visit_record)

    def _send_in_system_notification(self, specialist_user, visit_record):
        try:
            template = self.env.ref('odex_benefit.visit_notification_template', False)
            if template:
                body_html = template._render_field('body_html', [visit_record.id], compute_lang=True)[
                    visit_record.id]
            else:
                body_html = """
                                <div style="font-family: Arial, sans-serif; padding: 20px;">
                                    <h3>%s</h3>
                                    <p>%s %s,</p>
                                    <p>%s</p>
                                    <ul>
                                        <li><strong>%s</strong> %s</li>
                                        <li><strong>%s</strong> %s</li>
                                        <li><strong>%s</strong> %s</li>
                                    </ul>
                                    <p>%s</p>
                                    <p>%s<br/>%s</p>
                                </div>
                            """ % (
                    _('New File Assignment'),
                    _('Dear'), specialist_user.name,
                    _('A new file has been assigned to you:'),
                    _('Benefit File:'), self.benefit_ids[0].name or _('N/A'),
                    _('Visit Number:'), visit_record.name or visit_record.id,
                    _('Visit Date:'), visit_record.visit_date,
                    _('Please check your dashboard for more details.'),
                    _('Best regards,'), _('System')
                )

            partners = specialist_user.partner_id
            partners.message_post(
                body=body_html,
                partner_ids=partners.ids,
                subtype_id=self.env.ref('mail.mt_comment').id,
                content_subtype='html',
                email_layout_xmlid=False,
                notify_by_email=False,
            )

        except Exception as e:
            visit_record.message_post(
                body=_("New file assignment for %s. Visit #%s created.") % (
                    specialist_user.name,
                    visit_record.name or visit_record.id
                ),
                partner_ids=[specialist_user.partner_id.id],
                subtype_id=self.env.ref('mail.mt_note').id,
                notify_by_email=False,
            )
