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



class EmpowermentRequest(models.Model):
    _name = 'empowerment.request'
    _description = 'Empowerment Request'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    name = fields.Char(string='Request Number', readonly=True, default='New')
    request_date = fields.Datetime(string='Request Date', readonly=True, default=fields.Datetime.now)
    creator_id = fields.Many2one('res.users', string='Creator', default=lambda self: self.env.user, readonly=True)
    date_from = fields.Datetime(string='Date From')
    date_to = fields.Datetime(string='Date To')
    branch_id = fields.Many2one("branch.settings", string='Branch', domain="[('branch_type','=','branches')]")

    # Beneficiary Family
    familye_id = fields.Many2one('grant.benefit', string='Family')

    member_ids = fields.One2many(
        'family.member',
        compute='_compute_family_members',
        string='Family Member'
    )
    benefit_category_id = fields.Many2one(related='familye_id.benefit_category_id', string='Family Category', readonly=True)
    relationship = fields.Char(string='Beneficiary Relationship', readonly=True)

    identity_number = fields.Char(related='familye_id.id_number', string='ID Number', readonly=True)
    sms_phone = fields.Char(related='familye_id.sms_phone', string='Mobile Number', readonly=True)
    email = fields.Char(related='familye_id.email', string='Email', readonly=True)
    nationality = fields.Many2one(relates='familye_id.nationality_id', string='Nationality', readonly=True)
    education_status = fields.Selection(related='familye_id.education_status', string='Education Status', readonly=True)
    has_car = fields.Boolean(related='familye_id.has_car', string='Family Owns a Car?', readonly=True)
    health_status = fields.Selection(related='familye_id.health_status', string='Health Status')

    # Service Info
    service_id = fields.Many2one('services.settings', string='Service Item')
    service_type = fields.Selection(related='service_id.service_type', store=True)
    service_item = fields.Char(string="Service Element")

    # Education Info
    study_specialization = fields.Selection([
        ('bachelor', 'Bachelor'),
        ('diploma', 'Diploma')
    ], string='Study Specialization')

    university_id = fields.Many2one('empowerment.education.entity', string='University / College Name', domain="[('study_specialization','=','bachelor')]")
    institute_id = fields.Many2one('empowerment.education.entity', string='Institute / School Name', domain="[('study_specialization','=','diploma')]")

    intercession_type = fields.Selection([
        ('transfer', 'Transfer'),
        ('move', 'Move'),
        ('discount', 'Discount'),
        ('exemption', 'Exemption'),
    ], string='Intercession Type')

    request_entity_id = fields.Many2one('empowerment.education.entity', string='Requesting Entity')

    # Training Info
    training_type = fields.Selection([
        ('skill', 'Skill-based'),
        ('entrepreneurship', 'Entrepreneurship'),
        ('professional', 'Professional')
    ], string='Training Type')

    training_course_id = fields.Many2one('empowerment.qualification.course', string='Qualification Course')
    training_entity_id = fields.Many2one('empowerment.training.entity', string='Training Entity')

    training_intercession_type = fields.Selection([
        ('new_acceptance', 'New Acceptance'),
        ('transfer', 'Transfer'),
        ('relocation', 'Relocation'),
        ('discount', 'Discount'),
        ('exemption', 'Exemption')
    ], string="Training Intercession Type")

    # Funding Info
    project_funding_type_id = fields.Many2one('project.funding.type', string='Project Funding Type')
    sponsor_id = fields.Many2one('res.partner', string='Sponsor Name')
    sponsor_mobile = fields.Char(related='sponsor_id.mobile', readonly=True)
    sponsor_identity = fields.Char(related='sponsor_id.id_number', readonly=True)
    sponsor_email = fields.Char(related='sponsor_id.email', readonly=True)

    finance_request_entity_id = fields.Many2one('education.entity', string="Finance Request Entity")

    # Receiver
    request_receiver_id = fields.Many2one(
        'res.partner',
        string='Request Receiver',
        domain="[('is_empowerment_receiver', '=', True)]"
    )

    description = fields.Text(string='Description')

    # Request State
    state = fields.Selection([
        ('draft', 'Draft'),
        ('social_worker', 'Social Worker (Awaiting Execution)'),
        ('head_of_department', 'Head of Department'),
        ('branch_manager', 'Branch Manager'),
        ('finance', 'Finance Department'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    ], default='draft', string='Status', tracking=True)

    reject_reason = fields.Text(string='Rejection/Return Reason')
    return_reason = fields.Text(string='Return Reason')

    employment_history_ids = fields.One2many(
        comodel_name="hr.employee.history.req",
        inverse_name="employement_history"
    )
    qualifiction_id = fields.One2many(
        "hr.qualification.req",
        "qualification_relation_name",
        string="Qualifications"
    )

    def unlink(self):
        for order in self:
            if order.state not in ['draft']:
                raise UserError(_('You cannot delete this record State not Draft'))
        return super(EmpowermentRequest, self).unlink()


    @api.model
    def create(self, vals):
        if vals.get('name', 'New') == 'New':
            vals['name'] = self.env['ir.sequence'].next_by_code('empowerment.request') or 'New'
        return super(EmpowermentRequest, self).create(vals)

    def action_approve_social_worker(self):
        for rec in self:
            rec.state = 'social_worker'

    def action_approve_head(self):
        for rec in self:
            rec.state = 'head_of_department'

    def action_return_to_social_worker(self):
        for rec in self:
            rec.state = 'social_worker'

    def action_approve_branch(self):
        for rec in self:
            rec.state = 'branch_manager'

    def action_approve_finance(self):
        for rec in self:
            rec.state = 'finance'

    def action_approve_final(self):
        for rec in self:
            rec.state = 'approved'

    def action_reject(self):
        for rec in self:
            rec.state = 'rejected'

    def action_return_to_draft(self):
        # Open wizard to collect return reason - opens form view on 'empowerment.return.reason.wizard'
        return {
            'type': 'ir.actions.act_window',
            'name': _('سبب الإرجاع'),
            'view_mode': 'form',
            'res_model': 'empowerment.return.reason.wizard',
            'target': 'new',
            'context': {'default_request_id': self.id}
        }

    @api.depends('familye_id')
    def _compute_family_members(self):
        for rec in self:
            rec.member_ids = rec.familye_id.member_ids.ids if rec.familye_id else False




class ResPartner(models.Model):
    _inherit = 'res.partner'

    is_empowerment_receiver = fields.Boolean(string='Empowerment Beneficiary')


class EmpowermentReturnReasonWizard(models.TransientModel):
    _name = 'empowerment.return.reason.wizard'
    _description = 'Return Reason'

    request_id = fields.Many2one('empowerment.request', string='Request')
    reason = fields.Text(string='Reason', required=True)

    def action_return(self):
        self.ensure_one()
        if self.request_id:
            self.request_id.write({
                'state': 'draft',
                'return_reason': self.reason
            })
        # Close wizard window after saving
        return {'type': 'ir.actions.act_window_close'}
