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

from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError, UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
import logging

_logger = logging.getLogger(__name__)


class FamilyBankReportXlsx(models.AbstractModel):
    _name = 'report.odex_benefit.family_bank_report_xlsx'
    _description = 'Family Bank Report XLSX'
    _inherit = 'report.report_xlsx.abstract'

    @api.model
    def generate_xlsx_report(self, workbook, data, objs):
        try:
            # CHANGE: Use objs (wizard record) directly instead of data['lines']
            # This avoids passing large data through the client (HTTP/URL limits)
            wizard = objs
            _logger.info("=== FAMILY BANK REPORT START (Refactored) ===")
            _logger.info("Processing Wizard ID: %s", wizard.id)
            
            payment_orders = wizard.payment_order_ids
            _logger.info("Payment Orders: %s", len(payment_orders))
            
            moves = payment_orders.mapped('move_id')
            _logger.info("Moves: %s", len(moves))

            # Re-implement grouping logic here
            grouped = {}
            for move in moves:
                for line in move.line_ids.filtered(lambda l: l.debit > 0 and l.benefit_family_id):
                    family = line.benefit_family_id
                    key = family.id
                    if key not in grouped:
                        beneficiary_name = family.acc_holder_name or ''
                        beneficiary_id = family.acc_holder_id_number or ''
                        grouped[key] = {
                            'bank_name': (family.bank_id.bic or ''),
                            'account_number': 'SA' + (family.acc_number or ''),
                            'beneficiary_name': beneficiary_name,
                            'beneficiary_id': beneficiary_id,
                            'transfer_amount': 0.0,
                            'currency': 'SAR',
                            'family_code': family.code or '',
                            'purpose': 'Others',
                            'beneficiary_email': '', # Default value
                        }
                    grouped[key]['transfer_amount'] += float(line.debit or 0.0)
            
            lines = list(grouped.values())
            _logger.info("Total lines to process: %s", len(lines))
            
            sheet = workbook.add_worksheet(_('Family Bank Report'))

            header_format = workbook.add_format({
                'bold': True,
                'align': 'center',
                'valign': 'vcenter',
                'bg_color': '#4472C4',
                'font_color': 'white',
                'border': 1,
                'text_wrap': True
            })

            subheader_format = workbook.add_format({
                'bold': True,
                'align': 'center',
                'valign': 'vcenter',
                'bg_color': '#D3D3D3',
                'border': 1,
                'font_size': 9
            })

            normal = workbook.add_format({
                'align': 'center',
                'valign': 'vcenter',
                'border': 1
            })

            bold = workbook.add_format({
                'bold': True,
                'align': 'center',
                'valign': 'vcenter',
                'border': 1
            })

            sheet.set_row(0, 30)
            sheet.set_row(1, 25)
            sheet.set_row(2, 25)

            sheet.merge_range('A1:A2', 'Bank Name' + '\nاسم البنك', header_format)
            sheet.merge_range('B1:B2', 'Account Number(24N)' + '\nرقم الحساب', header_format)
            sheet.merge_range('C1:C2', 'Beneficiary Name' + '\nاسم المستفيد', header_format)
            sheet.merge_range('D1:D2', 'Amount(15)' + '\nقيمة الحوالة', header_format)
            sheet.merge_range('E1:E2', 'Civilian_Id(20)' + '\nرقم الهوية', header_format)
            sheet.merge_range('F1:F2', 'Currency (3N)' + '\nالعملة', header_format)
            sheet.merge_range('G1:G2', 'Beneficiaries Remarks (30)' + '\nملاحظات المستفيد', header_format)
            sheet.merge_range('H1:H2', 'Payment Purpose' + '\nغرض الدفع', header_format)
            sheet.merge_range('I1:I2', 'Beneficiary Email' + '\nالبريد الإلكتروني للمستفيد', header_format)

            row = 3
            total_amount = 0
            for idx, line in enumerate(lines):
                try:
                    sheet.write(row, 0, line['bank_name'], normal)
                    sheet.write(row, 1, line['account_number'], normal)
                    sheet.write(row, 2, line['beneficiary_name'], normal)
                    sheet.write_number(row, 3, line['transfer_amount'], normal)
                    sheet.write(row, 4, line['beneficiary_id'], normal)
                    sheet.write(row, 5, line['currency'], normal)
                    sheet.write(row, 6, line['family_code'], normal)
                    sheet.write(row, 7, line['purpose'], normal)
                    sheet.write(row, 8, line.get('beneficiary_email', ''), normal)
                    total_amount += line['transfer_amount']
                    row += 1
                except Exception as line_error:
                    _logger.error("ERROR processing line %s: %s", idx, line_error)
                    _logger.error("Line data: %s", line)
                    raise

            sheet.set_column('A:A', 25)
            sheet.set_column('B:B', 25)
            sheet.set_column('C:C', 30)
            sheet.set_column('D:D', 15)
            sheet.set_column('E:E', 20)
            sheet.set_column('F:F', 12)
            sheet.set_column('G:G', 25)
            sheet.set_column('H:H', 20)
            sheet.set_column('I:I', 30)
            
            _logger.info("=== FAMILY BANK REPORT SUCCESS: %s rows, total amount: %s ===", len(lines), total_amount)
            
        except Exception as e:
            _logger.error("=== FAMILY BANK REPORT FAILED ===")
            _logger.error("Error type: %s", type(e).__name__)
            _logger.error("Error message: %s", str(e))
            _logger.error("Data keys: %s", data.keys() if data else 'No data')
            _logger.error("Lines count: %s", len(data.get('lines', [])) if data else 0)
            import traceback
            _logger.error("Full traceback:\n%s", traceback.format_exc())
            raise
