import calendar
import logging
from datetime import date, datetime, timedelta
from decimal import Decimal, InvalidOperation

from django.db import transaction
from django.db.models import DecimalField, Q, Sum, Value
from django.db.models.functions import Coalesce
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from urllib.parse import urlencode
from django.views.decorators.http import require_POST

from NexusApp.models import Loan, LoanPayment
from NexusApp.utils.excel import date_range
from NexusApp.utils.staff_scope import get_staff_loan_or_404, staff_loans, staff_payments
from controllers.Admin.AdminloanreportController import (
    _in_range, collections_xlsx, history_in_range, history_xlsx, loan_reports_xlsx,
    payments_in_range,
)

logger = logging.getLogger(__name__)

MONEY = DecimalField(max_digits=14, decimal_places=2)
ZERO = Decimal('0')


# ----------------------------------------------------------------- helpers
def _int(value, default):
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


# due dates skip Sundays - see NexusApp/utils/loan_schedule.py
from NexusApp.utils.loan_schedule import (  # noqa: E402
    add_months as _add_months, loan_position, nth_due_date as _nth_due_date,
)


def _build_row(loan, today, ns='staff'):
    due_amount = loan.due_amount or ZERO
    paid = loan.paid or ZERO
    pos = loan_position(loan, paid, today)
    balance = pos['balance']
    paid_dues = pos['paid_dues']
    next_due = pos['next_due']

    return {
        'loan_id': loan.id,
        'customer_name': loan.customer_name,
        'phone_number': loan.phone_number,
        'place': loan.place.name,
        'place_id': loan.place_id,
        'loan_amount': float(loan.loan_amount),
        'paid_amount': float(paid),
        'pending_amount': float(balance),
        'balance_amount': float(balance),
        'total_payable': float(loan.total_payable),
        'due_amount': float(due_amount),
        'number_of_dues': loan.number_of_dues,
        'paid_dues': paid_dues,
        'pending_dues': loan.number_of_dues - paid_dues,
        'pending_days': pos['pending_days'],
        'overdue_amount': float(pos['overdue']),
        'due_number': min(paid_dues + 1, loan.number_of_dues),   # shown in Pay modal
        'payable_now': float(min(due_amount, balance)),          # default amount in Pay modal
        'payment_type': loan.get_payment_type_display(),
        'loan_date': loan.loan_date.strftime('%d/%m/%Y') if loan.loan_date else '-',
        'loan_date_iso': loan.loan_date.isoformat() if loan.loan_date else '',
        'next_due_date': next_due.strftime('%d/%m/%Y') if next_due else '-',
        'next_due_iso': next_due.isoformat() if next_due else '',
        'status': pos['status'],
        'paid_history_url': (
            f"{reverse(ns + ':paid_due_history')}?"
            f"{urlencode({'id': loan.id, 'place': loan.place.name})}"
        ),
        'invoice_url': f"{reverse(ns + ':payment_invoice')}?id={loan.id}",
        'period_report_url': f"{reverse(ns + ':loan_period_report')}?id={loan.id}",
    }


# def _collect_rows(request):
#     """Apply place / search / payment-type / due-date filters. Returns (rows, total)."""
#     place = request.GET.get('place', '').strip()
#     search = request.GET.get('search[value]', '').strip()
#     payment_type = request.GET.get('payment_type', '').strip().lower()
#     due_date = request.GET.get('due_date', '').strip()          # YYYY-MM-DD

#     qs = Loan.objects.select_related('place').annotate(
#         paid=Coalesce(Sum('payments__amount'), Value(0), output_field=MONEY)
#     )
#     if place:
#         qs = qs.filter(place__name__iexact=place)

#     total = qs.count()

#     if payment_type in ('daily', 'weekly', 'monthly'):
#         qs = qs.filter(payment_type=payment_type)
#     if search:
#         qs = qs.filter(
#             Q(customer_name__icontains=search) | Q(phone_number__icontains=search)
#         )

#     today = timezone.localdate()
#     rows = [_build_row(loan, today) for loan in qs.order_by('-id')]

#     # next due date / status are calculated, so they are filtered here, not in SQL
#     if due_date:
#         rows = [r for r in rows if r['next_due_iso'] == due_date]

#     return rows, total



def _collect_rows(request):
    """Apply place / search / payment-type / due-date filters.
    Completed loans are excluded from Loan Reports.
    """

    place = request.GET.get('place', '').strip()
    search = request.GET.get('search[value]', '').strip().lower()
    payment_type = request.GET.get('payment_type', '').strip().lower()
    due_date = request.GET.get('due_date', '').strip()
    start, end = date_range(request)                 # from_date / to_date on loan_date

    qs = staff_loans(request, Loan.objects.select_related('place', 'customer')).annotate(
        paid=Coalesce(
            Sum('payments__amount'),
            Value(0),
            output_field=MONEY
        )
    )

    if place:
        qs = qs.filter(place__name__iexact=place)

    today = timezone.localdate()

    # Build rows and exclude completed loans
    rows = [
        _build_row(loan, today)
        for loan in qs.order_by('-id')
    ]

    # Remove completed loans from Loan Reports
    rows = [
        row for row in rows
        if row['status'] != 'Completed'
    ]

    # Total active loans before search and other filters
    total = len(rows)

    # Payment type filter
    if payment_type in ('daily', 'weekly', 'monthly'):
        rows = [
            row for row in rows
            if row['payment_type'].lower() == payment_type
        ]

    # Customer name / phone search
    if search:
        rows = [
            row for row in rows
            if search in row['customer_name'].lower()
            or search in row['phone_number'].lower()
        ]

    # Due date filter
    if due_date:
        rows = [
            row for row in rows
            if row['next_due_iso'] == due_date
        ]

    # Loan date range (from_date / to_date)
    if start or end:
        rows = [row for row in rows if _in_range(row['loan_date_iso'], start, end)]

    return rows, total


# -------------------------------------------------------------- endpoints
SORT_KEYS = {
    1: lambda r: r['customer_name'].lower(),
    2: lambda r: r['balance_amount'],
    3: lambda r: r['loan_amount'],
    4: lambda r: r['due_amount'],
    5: lambda r: r['next_due_iso'] or '9999-99-99',
    6: lambda r: r['status'],
}


def loan_reports_data(request):
    if request.headers.get('x-requested-with') != 'XMLHttpRequest':
        return JsonResponse({'status': 'error', 'message': 'Invalid request.'}, status=400)

    draw = _int(request.GET.get('draw'), 1)
    try:
        start = max(_int(request.GET.get('start'), 0), 0)
        length = _int(request.GET.get('length'), 10)

        rows, total = _collect_rows(request)
        filtered = len(rows)

        order_col = _int(request.GET.get('order[0][column]'), -1)
        if order_col in SORT_KEYS:
            rows.sort(
                key=SORT_KEYS[order_col],
                reverse=request.GET.get('order[0][dir]', 'asc') == 'desc',
            )

        page = rows[start:] if length == -1 else rows[start:start + max(length, 1)]
        for i, row in enumerate(page, start=start + 1):
            row['DT_RowIndex'] = i

        return JsonResponse({
            'draw': draw,
            'recordsTotal': total,
            'recordsFiltered': filtered,
            'data': page,
        })

    except Exception:
        logger.exception('loan_reports_data failed')
        return JsonResponse({
            'draw': draw, 'recordsTotal': 0, 'recordsFiltered': 0, 'data': [],
            'error': 'Could not load loan reports.',
        }, status=500)


def loan_reports_export(request):
    """Excel of every loan (of the staff member's places) matching the filters."""
    rows, _ = _collect_rows(request)
    return loan_reports_xlsx(request, rows)


# ----------------------------------------------------------- record payment
@require_POST
def record_payment(request):
    """Save one collection (a LoanPayment row) from the Record Payment modal."""
    loan_id = request.POST.get('loan_id', '').strip()
    payment_date = request.POST.get('payment_date', '').strip()
    amount_raw = request.POST.get('paid_amount', '').strip()
    method = request.POST.get('payment_method', '').strip().lower()
    pay_status = request.POST.get('payment_status', '').strip().lower()

    errors = {}

    if not loan_id.isdigit():
        errors['loan_id'] = 'Loan is missing. Close the window and try again.'

    parsed_date = None
    if not payment_date:
        errors['payment_date'] = 'Payment date is required.'
    else:
        try:
            parsed_date = datetime.strptime(payment_date, '%Y-%m-%d').date()
            if parsed_date > timezone.localdate():
                errors['payment_date'] = 'Payment date cannot be in the future.'
        except ValueError:
            errors['payment_date'] = 'Invalid date format (use YYYY-MM-DD).'

    amount = None
    if not amount_raw:
        errors['paid_amount'] = 'Paid amount is required.'
    else:
        try:
            amount = Decimal(amount_raw)
            if not amount.is_finite() or amount <= 0:
                errors['paid_amount'] = 'Enter a valid positive paid amount.'
            elif amount != amount.quantize(Decimal('0.01')):
                errors['paid_amount'] = 'Paid amount can have at most 2 decimal places.'
        except InvalidOperation:
            errors['paid_amount'] = 'Enter a valid positive paid amount.'

    if method not in dict(LoanPayment.METHOD_CHOICES):
        errors['payment_method'] = 'Select a payment method.'
    if pay_status not in dict(LoanPayment.PAYMENT_STATUS_CHOICES):
        errors['payment_status'] = 'Select a payment status.'

    if errors:
        return JsonResponse({
            'status': 'error',
            'message': next(iter(errors.values())),
            'errors': errors,
        }, status=400)

    try:
        with transaction.atomic():
            # lock the loan row so two staff cannot overpay the same loan at once
            loan = staff_loans(request, Loan.objects.select_for_update()).filter(pk=int(loan_id)).first()
            if loan is None:
                return JsonResponse({'status': 'error', 'message': 'Loan not found.'}, status=404)
            if loan.status == 'completed':
                return JsonResponse(
                    {'status': 'error', 'message': 'This loan is already completed.'}, status=400)

            paid_so_far = loan.payments.aggregate(s=Sum('amount'))['s'] or ZERO
            pending = loan.total_payable - paid_so_far
            if amount > pending:
                return JsonResponse({
                    'status': 'error',
                    'message': f'Paid amount is more than the pending amount (\u20b9{pending:,.2f}).',
                    'errors': {'paid_amount': 'Amount exceeds pending amount.'},
                }, status=400)

            LoanPayment.objects.create(
                loan=loan,
                payment_date=parsed_date,
                amount=amount,
                collected_by=getattr(request, 'staff', None),
                payment_method=method,
                payment_status=pay_status,
            )

            new_pending = pending - amount
            if new_pending <= 0:                      # fully repaid -> close the loan
                loan.status = 'completed'
                loan.closed_date = parsed_date
                loan.save(update_fields=['status', 'closed_date', 'updated_at'])

        logger.info('payment recorded', extra={'loan_id': loan.id, 'amount': str(amount)})
        return JsonResponse({
            'status': 'success',
            'message': _payment_message(loan, amount, paid_so_far, new_pending),
            'pending_amount': float(new_pending),
            'loan_completed': new_pending <= 0,
        })

    except Exception:
        logger.exception('record_payment failed')
        return JsonResponse(
            {'status': 'error', 'message': 'Could not save the payment. Please try again.'},
            status=500)

# ------------------------------------------------------- paid due history
def _loan_with_paid(request, loan_id):
    """The loan (of the staff member's places) plus its total paid so far (.paid)."""
    return get_staff_loan_or_404(
        request,
        loan_id,
        Loan.objects.select_related('place', 'customer').annotate(
            paid=Coalesce(Sum('payments__amount'), Value(0), output_field=MONEY)
        ),
    )


def _history_rows(loan):
    """
    One row per payment, oldest first, with a running ledger so pending / extra
    can be shown per payment:

      need     = what was still owed on the current due just before this payment
      pending  = need - paid           (paid less than the due)
      extra    = paid - need           (paid ahead, goes to the next dues)

    A pending row shows "Cleared" once later payments have covered that due.
    """
    payments = list(
        loan.payments.select_related('collected_by').order_by('payment_date', 'id')
    )
    due = loan.due_amount or ZERO
    total_payable = loan.total_payable
    final_paid = sum((p.amount for p in payments), ZERO)

    rows, running = [], ZERO
    for i, p in enumerate(payments, start=1):
        done = (running % due) if due > 0 else ZERO          # already paid towards this due
        target = running - done + due if due > 0 else running + p.amount
        target = min(target, total_payable)                  # last due can be smaller
        need = max(target - running, ZERO)

        pending = max(need - p.amount, ZERO)
        extra = max(p.amount - need, ZERO)
        running += p.amount

        rows.append({
            'sno': i,
            'payment_date': p.payment_date.strftime('%d %B %Y'),
            'payment_date_iso': p.payment_date.isoformat(),
            'paid_due_amount': float(p.amount),
            'payment_method': p.get_payment_method_display(),
            'collected_by': p.collected_by.name if p.collected_by else '-',
            'pending_amount': float(pending),
            'pending_cleared': 'Yes' if final_paid >= target else 'No',
            'extra_amount': float(extra),
            'id': p.id,
            'collected_by_id': p.collected_by_id,
            'payment_method_code': p.payment_method,
        })
    return rows


def paid_due_history(request):
    """Page: /staff/paid_due_history/?id=<loan id>"""
    loan_id = request.GET.get('id', '').strip()
    if not loan_id.isdigit():
        raise Http404('Loan not found')

    loan = _loan_with_paid(request, int(loan_id))
    summary = _build_row(loan, timezone.localdate())

    return render(request, 'staffpanel/paid_due_history.html', {
        'loan': loan,
        'summary': summary,
        'place_name': loan.place.name,
        'total_amount': float(loan.total_payable),
    })


HISTORY_SORT_KEYS = {
    1: lambda r: (r['payment_date_iso'], r['id']),
    2: lambda r: r['paid_due_amount'],
    3: lambda r: r['pending_amount'],
    4: lambda r: r['extra_amount'],
}


def _history_filtered(request):
    loan_id = request.GET.get('id', '').strip()
    if not loan_id.isdigit():
        return None
    loan = get_staff_loan_or_404(request, int(loan_id))
    rows = history_in_range(request, _history_rows(loan))

    search = request.GET.get('search[value]', '').strip().lower()
    if search:
        rows = [
            r for r in rows
            if search in r['payment_date'].lower()
            or search in r['payment_method'].lower()
            or search in r['collected_by'].lower()
            or search in str(r['paid_due_amount'])
        ]
    return loan, rows


def paid_due_history_data(request):
    if request.headers.get('x-requested-with') != 'XMLHttpRequest':
        return JsonResponse({'status': 'error', 'message': 'Invalid request.'}, status=400)

    draw = _int(request.GET.get('draw'), 1)
    try:
        result = _history_filtered(request)
        if result is None:
            return JsonResponse({'status': 'error', 'message': 'Loan is missing.'}, status=400)
        loan, rows = result

        # correction requests (admin approval) - staff may correct only their own entries
        from controllers.PaymentEditController import pending_edit_map
        edit_map = pending_edit_map([r['id'] for r in rows])
        me = getattr(getattr(request, 'staff', None), 'pk', None)
        for r in rows:
            r['edit_status'] = edit_map.get(r['id'], '')
            r['can_edit'] = r['collected_by_id'] == me and r['edit_status'] != 'pending'

        total = loan.payments.count()
        filtered = len(rows)

        order_col = _int(request.GET.get('order[0][column]'), -1)
        if order_col in HISTORY_SORT_KEYS:
            rows.sort(
                key=HISTORY_SORT_KEYS[order_col],
                reverse=request.GET.get('order[0][dir]', 'asc') == 'desc',
            )
        else:
            rows.reverse()                       # default: newest payment first

        start = max(_int(request.GET.get('start'), 0), 0)
        length = _int(request.GET.get('length'), 10)
        page = rows[start:] if length == -1 else rows[start:start + max(length, 1)]

        return JsonResponse({
            'draw': draw,
            'recordsTotal': total,
            'recordsFiltered': filtered,
            'data': page,
        })

    except Http404:
        return JsonResponse({'status': 'error', 'message': 'Loan not found.'}, status=404)
    except Exception:
        logger.exception('paid_due_history_data failed')
        return JsonResponse({
            'draw': draw, 'recordsTotal': 0, 'recordsFiltered': 0, 'data': [],
            'error': 'Could not load payment history.',
        }, status=500)


def paid_due_history_export(request):
    result = _history_filtered(request)
    if result is None:
        return HttpResponse('Loan is missing.', status=400)
    loan, rows = result
    return history_xlsx(request, loan, rows)

# dashboard  page

def _my_payments(request):
    """This staff member's own collections (of their places) inside the date range."""
    staff = getattr(request, 'staff', None)
    if staff is None:
        return LoanPayment.objects.none(), {}
    return payments_in_range(
        request, staff_payments(request, LoanPayment.objects.filter(collected_by=staff)))


def collections_export(request):
    """Excel of the staff member's collections in the selected payment-date range."""
    payments, paid_map = _my_payments(request)
    return collections_xlsx(request, payments, paid_map, filename='my_collections')


def today_collections_data(request):
    # from_date / to_date range (or the old single ?date=), default = today
    payments, paid_map = _my_payments(request)

    data = []
    total = cash = upi = 0
    for i, p in enumerate(payments, start=1):
        loan = p.loan
        balance = max(loan.total_payable - paid_map.get(loan.id, 0), 0)
        total += p.amount
        if p.payment_method == 'cash':
            cash += p.amount
        elif p.payment_method == 'upi':
            upi += p.amount
        data.append({
            'sno': i,
            'loan_id': loan.id,
            'customer': loan.customer_name,
            'phone': loan.phone_number,
            'place': loan.place.name,
            'payment_type': loan.get_payment_type_display(),
            'payment_method': p.get_payment_method_display(),
            'payment_date': p.payment_date.isoformat(),
            'amount': float(p.amount),
            'payment_status': p.get_payment_status_display(),
            'loan_balance': float(balance),
        })

    return JsonResponse({
        'data': data,
        'summary': {
            'total': float(total), 'cash': float(cash),
            'upi': float(upi), 'count': len(data),
        },
    })

# today collection section collection list page data view function 
def collection_list_data(request):
    # from_date / to_date range (or the old single ?date=), default = today
    payments, paid_map = _my_payments(request)

    data = []
    for i, p in enumerate(payments, start=1):
        loan = p.loan
        balance = max(loan.total_payable - paid_map.get(loan.id, 0), 0)
        data.append({
            'sno': i,
            'loan_id': loan.id,
            'customer': loan.customer_name,
            'phone': loan.phone_number,
            'place': loan.place.name,
            'staff': p.collected_by.name if p.collected_by else '-',
            'payment_type': loan.get_payment_type_display(),
            'payment': p.get_payment_method_display(),
            'payment_date': p.payment_date.isoformat(),
            'amount': float(p.amount),
            'pending_amount': float(balance),
            'pending_cleared': 'Yes' if p.payment_status == 'completed' else 'No',
            'extra_amount': 0,
            'extra_cleared': 'No',
        })
    return JsonResponse({'data': data})

# ------------------------------------------------- shared with the admin side
from controllers.Admin.AdminloanreportController import (  # noqa: E402
    _parse_day, _payment_message, collection_totals, period_report_payload,
)


def loan_reports_summary(request):
    """Collection cards on Loan Reports - only the staff member's locations."""
    qs = staff_loans(request, Loan.objects.all())
    place = request.GET.get('place', '').strip()
    if place:
        qs = qs.filter(place__name__iexact=place)
    return JsonResponse(collection_totals(qs, _parse_day(request.GET.get('date'))))


def loan_period_report(request):
    loan_id = request.GET.get('id', '').strip()
    if not loan_id.isdigit():
        return JsonResponse({'status': 'error', 'message': 'Loan is missing.'}, status=400)
    loan = staff_loans(request, Loan.objects.select_related('customer')).filter(pk=int(loan_id)).first()
    if loan is None:
        return JsonResponse({'status': 'error', 'message': 'Loan not found.'}, status=404)
    return JsonResponse(period_report_payload(loan))
