from odoo import models, fields, api

class ResPartnerLoan(models.Model):
    _inherit = "res.partner"


    loan_inprogress_count = fields.Integer(
        string="In Progress Loans",
        compute="_compute_loan_counts"
    )
    loan_total_count = fields.Integer(
        string="Total Loans",
        compute="_compute_loan_counts"
    )

    loan_count = fields.Char(
        string="Loan",
        compute="_compute_loan_counts"
    )
    loan_amount = fields.Float(
        string="Loan Amount",
        compute="_compute_loan_summary"
    )
    capital = fields.Float(
        string="Capital",
        compute="_compute_loan_summary"
    )
    interest = fields.Float(
        string="Interest",
        compute="_compute_loan_summary"
    )
    due_tag = fields.Char(
        string="Due Tag",
        compute="_compute_loan_summary"
    )
    loan_ids = fields.One2many(
        'loan.management',
        'partner_id',
        string="Loans"
    )

    def _compute_loan_counts(self):
        Loan = self.env["loan.management"]

        for partner in self:
            total = Loan.search_count([("partner_id", "=", partner.id)])
            inprogress = Loan.search_count([
                ("partner_id", "=", partner.id),
                ("loan_stage", "=", "inprogress")
            ])

            partner.loan_inprogress_count = inprogress
            partner.loan_total_count = total
            partner.loan_count = f"{inprogress} / {total}"


    def action_view_customer_loans(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': 'Customer Loans',
            'res_model': 'loan.management',
            'view_mode': 'list,form',
            'domain': [
                ('partner_id', '=', self.id),
            ],
            'context': {
                'default_partner_id': self.id,
                'search_default_inprogress': 1,
            },
        }


    def _compute_loan_summary(self):
        Loan = self.env['loan.management']
       

        for partner in self:
            loans = Loan.search([
                ('partner_id', '=', partner.id),
                ('loan_stage', '=', 'inprogress')
            ])

            partner.loan_amount = sum(loans.mapped('loan_amount'))
            partner.capital = sum(loans.mapped('remaining_capital'))
            partner.interest = sum(loans.mapped('remaining_interest'))
            
            partner.due_tag = 'DUE' if partner.interest > 0 else ''
