# -*- coding: utf-8 -*-
from datetime import date

from dateutil.relativedelta import relativedelta

from odoo import api, fields, models


class TimesheetV2Dashboard(models.TransientModel):
    """Overview panel — office and personal target gauges."""

    _name = 'timesheet.v2.dashboard'
    _description = 'Time Sheet V2 Overview'

    date_from = fields.Date(
        string='Start Date',
        default=lambda self: date.today().replace(day=1),
    )
    date_to = fields.Date(
        string='End Date',
        default=lambda self: date.today().replace(day=1) + relativedelta(months=1, days=-1),
    )
    employee_id = fields.Many2one(
        comodel_name='hr.employee',
        string='User',
        default=lambda self: self.env['hr.employee'].search(
            [('user_id', '=', self.env.uid)], limit=1,
        ),
    )

    office_target_hours = fields.Float(compute='_compute_stats')
    office_actual_hours = fields.Float(compute='_compute_stats')
    office_target_revenue = fields.Monetary(compute='_compute_stats', currency_field='currency_id')
    office_actual_revenue = fields.Monetary(compute='_compute_stats', currency_field='currency_id')
    office_progress = fields.Float(compute='_compute_stats')

    my_target_hours = fields.Float(compute='_compute_stats')
    my_actual_hours = fields.Float(compute='_compute_stats')
    my_target_revenue = fields.Monetary(compute='_compute_stats', currency_field='currency_id')
    my_actual_revenue = fields.Monetary(compute='_compute_stats', currency_field='currency_id')
    my_progress = fields.Float(compute='_compute_stats')

    internal_hours = fields.Float(compute='_compute_stats')
    billable_hours = fields.Float(compute='_compute_stats')
    non_billable_hours = fields.Float(compute='_compute_stats')
    total_hours = fields.Float(compute='_compute_stats')

    currency_id = fields.Many2one(
        comodel_name='res.currency',
        default=lambda self: self.env.company.currency_id,
    )

    @api.depends('date_from', 'date_to', 'employee_id')
    def _compute_stats(self):
        AnalyticLine = self.env['account.analytic.line']
        for rec in self:
            domain = [('project_id', '!=', False)]
            if rec.date_from:
                domain.append(('date', '>=', rec.date_from))
            if rec.date_to:
                domain.append(('date', '<=', rec.date_to))

            all_lines = AnalyticLine.search(domain)
            billable_lines = all_lines.filtered('is_billable')
            internal_lines = all_lines.filtered('is_internal')
            non_billable = all_lines.filtered(lambda l: not l.is_billable)

            office_employees = self.env['hr.employee'].search([
                ('include_in_office_target', '=', True),
            ])
            office_target_hours = sum(office_employees.mapped('target_hours'))
            office_actual_hours = sum(billable_lines.mapped('unit_amount'))
            office_actual_revenue = sum(billable_lines.mapped('amount'))
            office_target_revenue = sum(office_employees.mapped('monthly_revenue_target'))

            employee = rec.employee_id
            my_lines = billable_lines
            if employee:
                my_lines = my_lines.filtered(lambda l: l.employee_id == employee)
            my_target_hours = employee.target_hours if employee else 0.0
            my_actual_hours = sum(my_lines.mapped('unit_amount'))
            my_actual_revenue = sum(my_lines.mapped('amount'))
            my_target_revenue = employee.monthly_revenue_target if employee else 0.0

            rec.office_target_hours = office_target_hours
            rec.office_actual_hours = round(office_actual_hours, 1)
            rec.office_target_revenue = office_target_revenue
            rec.office_actual_revenue = office_actual_revenue
            rec.office_progress = (
                (office_actual_hours / office_target_hours * 100)
                if office_target_hours else 0.0
            )

            rec.my_target_hours = my_target_hours
            rec.my_actual_hours = round(my_actual_hours, 1)
            rec.my_target_revenue = my_target_revenue
            rec.my_actual_revenue = my_actual_revenue
            rec.my_progress = (
                (my_actual_hours / my_target_hours * 100)
                if my_target_hours else 0.0
            )

            rec.internal_hours = round(sum(internal_lines.mapped('unit_amount')), 1)
            rec.billable_hours = round(sum(billable_lines.mapped('unit_amount')), 1)
            rec.non_billable_hours = round(sum(non_billable.mapped('unit_amount')), 1)
            rec.total_hours = round(sum(all_lines.mapped('unit_amount')), 1)

    def action_open_my_timesheet(self):
        self.ensure_one()
        return self.env.ref('jb_timesheet_v2.action_timesheet_v2_my_timesheet').read()[0]
