from odoo import fields, models, api, _


class ServicesSettings(models.Model):
    _name = 'services.settings'
    _rec_name = 'service_name'
    _order = 'service_number'

    service_name = fields.Char(string='Service Name')
    benefit_type = fields.Selection(string='Benefit Type', selection=[('family', 'Family'), ('member', 'Member')])
    parent_service = fields.Many2one('services.settings', string='Parent Service')
    is_main_service = fields.Boolean(string='Is Main Service?')
    is_service_producer = fields.Boolean(string='Is Service Producer?')
    service_producer_id = fields.Many2one('res.partner', string='Service Producer')
    is_this_service_for_student = fields.Boolean(string='Is Service For Student?')
    service_type = fields.Selection(
        [('rent', 'Rent'), ('home_restoration', 'Home Restoration'), ('alternative_housing', 'Alternative Housing'),
         ('home_maintenance', 'Home Maintenance')
            , ('complete_building_house', 'Complete Building House'), ('electrical_devices', 'Electrical Devices'),
         ('home_furnishing', 'Home furnishing')
            , ('electricity_bill', 'Electricity bill'), ('water_bill', 'Water bill'), ('buy_car', 'Buy Car'),
         ('recruiting_driver', 'Recruiting Driver')
            , ('transportation_insurance', 'Transportation Insurance'), ('debits', 'Debits'),
         ('health_care', 'Health Care'),
         ('providing_medicines_medical_devices_and_needs_the_disabled',
          'Providing Medicines Medical Devices And Needs The Disabled'),
         ('recruiting_domestic_worker_or_nurse', 'Recruiting a domestic worker or nurse'), ('marriage', 'Marriage'),
         ('eid_gift', 'Eid gift'),
         ('winter_clothing', 'Winter clothing'), ('ramadan_basket', 'Ramadan basket'),
         ('natural_disasters', 'Natural disasters'),
         ('legal_arguments', 'Legal arguments'), ('buy_home', 'Buy Home'), ('main_service', 'Main Service'),
         ('normal_service', 'Normal Service')]
        , string='Service Type')
    raise_amount_for_orphan = fields.Float(string='Raise Amount For Orphan')
    rent_lines = fields.One2many('rent.lines', 'services_settings_id')
    attachment_lines = fields.One2many('service.attachments.settings', 'service_id')
    # Fields for home restoration
    category_amount_lines = fields.One2many('category.amount.line', 'services_settings_id')
    rent_amount_for_alternative_housing = fields.Float(string='Rent Amount For Alternative Housing')
    rent_period = fields.Integer('Rent Period')
    home_maintenance_lines = fields.One2many('home.maintenance.lines', 'services_settings_id')
    benefit_category_ids = fields.Many2many('benefit.category', string='Allowed Categories')
    account_id = fields.Many2one('account.account', string='Expenses Account', domain="[('user_type_id.id','=',15)]")
    accountant_id = fields.Many2one('res.users', string='Accountant')
    # For Electrical Devices
    electrical_devices_lines = fields.One2many('electrical.devices', 'services_settings_id')
    # Home Furnishing
    home_furnishing_lines = fields.One2many('home.furnishing.lines', 'services_settings_id')
    max_furnishing_amount_if_exception = fields.Float(string='Max Furnishing Amount (Exception)')
    bill_lines = fields.One2many('bill.lines', 'services_settings_id')
    min_count_member = fields.Integer(string='Mini Count Member')
    member_max_payroll = fields.Float(string='Member Max Payroll')
    fatherless_member_amount = fields.Float(string='Fatherless Member Amount')
    orphan_member_amount = fields.Float(string='Orphan Member Amount')
    # Buy Home
    limit_person_line_ids = fields.One2many('service.limit.person.line', 'services_settings_id')
    buy_home_max_total_amount = fields.Float(string='Buy Home Max Total Amount')
    home_age = fields.Integer(string='Home Age')
    required_attach = fields.Boolean(string='Required Attach')
    is_seasonal_service = fields.Boolean(string='Is Seasonal Service?')
    active = fields.Boolean('Active', default=True)
    show_in_portal = fields.Boolean(string="Show in Portal", copy=False)
    service_number = fields.Char(string="Service Number", copy=False)
    service_category = fields.Selection([
        ('emergency', 'Emergency'),
        ('permanent', 'Permanent'),
        ('exceptional', 'Exceptional'),
        ('seasonal', 'Seasonal'),
    ], string="Service Category", copy=False)
    company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.user.company_id)
    currency_id = fields.Many2one('res.currency', string="Currency", related='company_id.currency_id')
    max_amount = fields.Monetary(string="Maximum Amount", currency_field='currency_id', copy=False)
    max_age = fields.Integer(string="Maximum Age", copy=False)
    service_description = fields.Text(string="Service Description")
    service_conditions = fields.Html(string="Service Conditions")
    allowed_recurrence = fields.Selection([
        ('once', 'Once'),
        ('periodic', 'Every Period'),
        ('unlimited', 'Unlimited'),
    ], string="Allowed Recurrence", default='once')
    recurrence_period = fields.Selection([
        ('months', 'Months'),
        ('years', 'Years'), ],
        string="Recurrence Period", default='months'
    )
    recurrence_interval = fields.Integer(
        string="Recurrence Interval",
        default=1,
    )
    requires_visit = fields.Boolean(
        string="Requires Visit?"
    )
    max_limit_type = fields.Selection([
        ('none', 'No Limit'),
        ('fixed', 'Fixed Amount'),
        ('amount_person', 'Amount by Individuals'),
        ('category', 'Amount by Category'),
        ('category_person', 'Amount by Category and Individuals'),
        ('region', 'Amount by Region'),
        ('service', 'Amount by Service'),
    ], string="Max Limit Type"
    )
    needs_beneficiary_manager_approval = fields.Boolean("Needs Beneficiary Manager Approval")
    needs_services_head_approval = fields.Boolean(string="Needs Services Head Approval")
    needs_legal_approval = fields.Boolean(string="Needs Legal Approval")
    needs_project_management_approval = fields.Boolean(string="Needs Project Management Approval")
    allow_non_beneficiary = fields.Boolean(string="Allow Non Beneficiary")
    max_limit_period = fields.Selection([
        ('request', 'Per Request'),
        ('individual', 'Per Individual'),
        ('month', 'Per Month'),
        ('year_from_request', 'Year from date of request'),
        ('calendar_year', 'Calendar year'),
    ], string='Maximum Limit Period')
    allowed_period = fields.Integer(
        string='Allowed Period', default=1,
        help='Specify the allowed number of months or years based on the selected period type.'
    )
    max_months_limit = fields.Integer(
        string='Maximum Number of Months',
        help='Specify the maximum allowed number of months when the period type is monthly.'
    )
    in_kind = fields.Boolean(string="In Kind")
    payment_method = fields.Selection([
        ('none', 'None'),
        ('payment_order', 'Payment Order'),
        ('invoice', 'Invoice'),
    ], string='Payment Method', default="payment_order")
    family_related_fields = fields.Many2many(
        comodel_name='ir.model.fields',
        relation='services_settings_family_field_rel',
        column1='services_settings_id',
        column2='field_id',
        string='Related Family Fields',
        domain="[('model_id.model', '=', 'grant.benefit')]",
        help="Select fields from the Family profile (grant.benefit) to display in the service request."
    )

    member_related_fields = fields.Many2many(
        comodel_name='ir.model.fields',
        relation='services_settings_member_field_rel',
        column1='services_settings_id',
        column2='field_id',
        string='Related Member Fields',
        domain="[('model_id.model', '=', 'family.member')]",
        help="Select fields from the Member profile to display only when the service is for a member."
    )
    allowed_country_ids = fields.Many2many(
        comodel_name='res.country',
        relation='services_settings_country_rel',
        column1='service_id',
        column2='country_id',
        string='Allowed Countries',
        help='Countries where this service is available. Leave empty to allow all countries.'
    )

    @api.onchange('benefit_type')
    def _onchange_benefit_type(self):
        if self.benefit_type != 'member':
            self.member_related_fields = [(5, 0, 0)]

    @api.onchange('max_limit_period')
    def _onchange_max_limit_period(self):
        if self.max_limit_period not in ['year_from_request', 'calendar_year']:
            self.allowed_period = 0


class RentLines(models.Model):
    _name = 'rent.lines'

    benefit_category_id = fields.Many2one('benefit.category', string='Benefit Category')
    services_settings_id = fields.Many2one('services.settings', string='Services Settings')
    benefit_count = fields.Integer('Benefit Count')
    estimated_rent_branches = fields.Float(string='Estimated Rent Branches')
    estimated_rent_governorate = fields.Float(string='Estimated Rent Governorate')
    discount_rate_shared_housing = fields.Float(string='Discount Rate For Shared housing')

    _sql_constraints = [
        (
            'uniq_category_count',
            'UNIQUE(benefit_category_id, benefit_count)',
            _("Couldn't create same benefit category and count")
        )
    ]


class CategoryAmountLine(models.Model):
    _name = 'category.amount.line'

    benefit_category_id = fields.Many2one('benefit.category', string='Benefit Category')
    services_settings_id = fields.Many2one('services.settings', string='Services Settings')
    max_amount = fields.Float(string='Max Amount')


class HomeMaintenanceLines(models.Model):
    _name = 'home.maintenance.lines'
    _rec_name = 'maintenance_name'

    services_settings_id = fields.Many2one('services.settings', string='Services Settings')
    maintenance_name = fields.Char(string='Maintenance Name')


class ElectricalDevices(models.Model):
    _name = 'electrical.devices'
    _rec_name = 'device_name'

    min_count_member = fields.Integer(string='From')
    max_count_member = fields.Integer(string='To')
    device_name = fields.Char(string="Device Name")
    allowed_quantity = fields.Integer(string='Allowed Quantity')
    account_id = fields.Many2one('account.account', string='Expenses Account', domain="[('user_type_id.id','=',15)]")
    services_settings_id = fields.Many2one('services.settings')
    price_unit = fields.Float()
    product_ids = fields.Many2many(
        comodel_name='product.product',
        relation='electrical_device_product_rel',
        column1='electrical_device_id',
        column2='product_id',
        string='Allowed Products',
        domain = "[('type', '=', 'product')]"
    )


class HomeFurnishingLines(models.Model):
    _name = 'home.furnishing.lines'

    services_settings_id = fields.Many2one('services.settings')
    name = fields.Char(string="Furnishing Name")
    max_furnishing_amount = fields.Float(string='Furnishing Amount')


class BillLines(models.Model):
    _name = 'bill.lines'

    benefit_category_id = fields.Many2one('benefit.category', string='Benefit Category')
    min_count_member = fields.Integer(string='From')
    max_count_member = fields.Integer(string='To')
    max_amount_for_bill = fields.Float(string='Max Amount For Bill')
    services_settings_id = fields.Many2one('services.settings', string='Services Settings')


class ServiceLimitByPersonLine(models.Model):
    _name = 'service.limit.person.line'

    min_count_member = fields.Integer(string='Minimum Number of Persons')
    max_count_member = fields.Integer(string='Maximum Number of Persons')
    amount = fields.Float(string='Amount')
    services_settings_id = fields.Many2one('services.settings', string='Services Settings')
