import logging
import re

from django.db import IntegrityError, transaction
from django.db.models import Count, Max, Q
from django.http import JsonResponse
from django.urls import reverse
from django.views.decorators.http import require_POST
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from NexusApp.models import Customer, Loan, Place
from NexusApp.utils.staff_scope import staff_customers, staff_loans, staff_places

logger = logging.getLogger(__name__)

# The validation rules are identical to the admin side, so reuse them.
from controllers.Admin.AddLoanController import (
    MAX_NOTES,
    MAX_PLACE,
    TOTAL_LIMIT,
    _customer_form_data,
    _json_error,
    _parse_date,
    _parse_money,
    _validate_customer,
)

logger = logging.getLogger(__name__)


# ----------------------------- add loan -----------------------------------
def staff_addloan(request):
    logger.info("loan creation started", extra={'method': request.method})

    if request.method != 'POST':
        return _json_error('Invalid request method.', 405)

    customer_data = _customer_form_data(request)
    aadhaar_photo = request.FILES.get('aadhaar_photo')

    place = ' '.join(request.POST.get('place', '').split())

    loan_date = request.POST.get('loan_date', '').strip()
    loan_amount = request.POST.get('loan_amount', '').strip()
    payment_type = request.POST.get('payment_type', '').strip()
    first_due_date = request.POST.get('first_due_date', '').strip()
    number_of_dues = request.POST.get('number_of_dues', '').strip()
    due_amount = request.POST.get('due_amount', '').strip()
    notes = request.POST.get('notes', '').strip()

    errors = _validate_customer(customer_data, aadhaar_photo, referral_required=True)

    place_obj = None
    if not place:
        errors['place'] = "Select a place."
    elif len(place) > MAX_PLACE:
        errors['place'] = f"Place cannot exceed {MAX_PLACE} characters."
    else:
        # a collection agent can only add loans in the places assigned to them
        place_obj = staff_places(request).filter(name__iexact=place).first()
        if place_obj is None:
            errors['place'] = "You can only add loans for your assigned locations."

    parsed_loan_date = None
    if not loan_date:
        errors['loan_date'] = "Loan date is required."
    else:
        parsed_loan_date = _parse_date(loan_date)
        if not parsed_loan_date:
            errors['loan_date'] = "Invalid date format (use YYYY-MM-DD)."

    amount = None
    if not loan_amount:
        errors['loan_amount'] = "Loan amount is required."
    else:
        amount = _parse_money(loan_amount)
        if amount is None:
            errors['loan_amount'] = "Enter a valid positive loan amount (max 2 decimals)."

    valid_payment_types = [value for value, _ in Loan.PAYMENT_TYPE_CHOICES]
    if not payment_type:
        errors['payment_type'] = "Payment type is required."
    elif payment_type not in valid_payment_types:
        errors['payment_type'] = "Select a valid payment type."

    parsed_first_due = None
    if not first_due_date:
        errors['first_due_date'] = "First due date is required."
    else:
        parsed_first_due = _parse_date(first_due_date)
        if not parsed_first_due:
            errors['first_due_date'] = "Invalid date format (use YYYY-MM-DD)."
        elif parsed_loan_date and parsed_first_due < parsed_loan_date:
            errors['first_due_date'] = "First due date cannot be before the loan date."
        elif parsed_first_due.weekday() == 6:
            errors['first_due_date'] = "First due date cannot be a Sunday (no dues on Sundays)."

    dues = None
    if not number_of_dues:
        errors['number_of_dues'] = "Number of dues is required."
    elif not re.fullmatch(r'[0-9]{1,9}', number_of_dues) or int(number_of_dues) <= 0:
        errors['number_of_dues'] = "Enter a valid number of dues."
    else:
        dues = int(number_of_dues)

    per_due = None
    if not due_amount:
        errors['due_amount'] = "Due amount is required."
    else:
        per_due = _parse_money(due_amount)
        if per_due is None:
            errors['due_amount'] = "Enter a valid positive due amount."

    if 'due_amount' not in errors and 'number_of_dues' not in errors:
        if per_due * dues >= TOTAL_LIMIT:
            errors['number_of_dues'] = "Total payable is too large for the given due amount."

    if not notes:
        errors['notes'] = "Notes are required."
    elif len(notes) > MAX_NOTES:
        errors['notes'] = f"Notes cannot exceed {MAX_NOTES} characters."

    if errors:
        logger.warning("loan creation failed due to validation errors.",
                       extra={'errors': errors})
        return JsonResponse({'status': 'error', 'errors': errors}, status=400)

    try:
        with transaction.atomic():
            # One Customer per Aadhaar number: reuse it, otherwise create it.
            # The Loan only stores the FK (customer details are NOT Loan fields).
            customer = Customer.objects.select_for_update().filter(
                aadhaar_number=customer_data['aadhaar_number']
            ).first()
            if customer is None:
                customer = Customer(aadhaar_number=customer_data['aadhaar_number'])

            customer.customer_name = customer_data['customer_name']
            customer.phone_number = customer_data['phone_number']
            customer.address = customer_data['address']
            customer.referral_name = customer_data['referral_name']
            customer.referral_phone = customer_data['referral_phone']
            if aadhaar_photo:
                customer.aadhaar_photo = aadhaar_photo
            customer.save()

            loan = Loan.objects.create(
                customer=customer,
                place=place_obj,
                staff=getattr(request, 'staff', None),
                loan_date=parsed_loan_date,
                loan_amount=amount,
                payment_type=payment_type,
                first_due_date=parsed_first_due,
                number_of_dues=dues,
                due_amount=per_due,
                notes=notes,
            )

        logger.info("loan created successfully", extra={'loan_id': loan.id})
        return JsonResponse({
            'status': 'success',
            'message': 'Loan added successfully.',
            'redirect_url': reverse('staff:loan_registers'),
        })

    except IntegrityError:
        logger.exception("loan creation failed due to a database integrity error.")
        return _json_error("Loan could not be saved because of a database constraint.")
    except Exception:
        logger.exception("loan creation failed.")
        return _json_error("Loan could not be added. Please try again.", 500)


# ------------------- Aadhaar lookup (auto-fill on add loan) ----------------
@require_POST
def staff_get_loan_customer_details(request):
    aadhaar_number = request.POST.get('aadhaar_number', '').strip()

    if not re.fullmatch(r'[0-9]{12}', aadhaar_number):
        return _json_error('Enter a valid 12-digit Aadhaar number.')

    customer = Customer.objects.filter(aadhaar_number=aadhaar_number).first()
    if not customer:
        return JsonResponse({
            'status': 'not_found',
            'message': 'No existing customer found.'
        }, status=404)

    last_loan = customer.loans.select_related('place').first()   # Meta ordering = -id

    return JsonResponse({
        'status': 'success',
        'data': {
            'phone_number': customer.phone_number,
            'place': last_loan.place.name if last_loan else '',
            'customer_name': customer.customer_name,
            'address': customer.address,
            'referral_name': customer.referral_name or '',
            'referral_phone': customer.referral_phone or '',
            'aadhaar_photo': customer.aadhaar_photo.url if customer.aadhaar_photo else '',
        }
    })


# ----------------------------- customer list -------------------------------
def staff_view_all_customer(request):
    if request.headers.get('x-requested-with') != 'XMLHttpRequest':
        return _json_error('Invalid request.')

    draw = 1
    try:
        draw = int(request.GET.get('draw', 1))
        start = max(int(request.GET.get('start', 0)), 0)
        length = int(request.GET.get('length', 10))
        search = request.GET.get('search[value]', '').strip()
        order_col = request.GET.get('order[0][column]', '1')
        order_dir = request.GET.get('order[0][dir]', 'asc')

        customers = staff_customers(request)
        records_total = customers.count()

        if search:
            customers = customers.filter(
                Q(customer_name__icontains=search) |
                Q(phone_number__icontains=search) |
                Q(aadhaar_number__icontains=search) |
                Q(id__in=staff_loans(request).filter(
                    place__name__icontains=search).values('customer_id'))
            )
        records_filtered = customers.count()

        my_place_ids = list(staff_places(request).values_list('id', flat=True))
        customers = customers.annotate(
            total_chits=Count('loans', filter=Q(loans__place_id__in=my_place_ids)),
            latest_loan_id=Max('loans__id', filter=Q(loans__place_id__in=my_place_ids)),
        )

        order_map = {'1': 'customer_name', '2': 'total_chits'}
        if order_col in order_map:
            field = order_map[order_col]
            if order_dir == 'desc':
                field = '-' + field
            customers = customers.order_by(field, '-id')
        else:
            customers = customers.order_by('-id')

        rows = list(customers[start:] if length == -1 else customers[start:start + length])

        # latest place of each customer, fetched in one query
        latest_ids = [c.latest_loan_id for c in rows if c.latest_loan_id]
        place_by_loan = {
            loan.id: loan.place.name
            for loan in Loan.objects.filter(id__in=latest_ids).select_related('place')
        }

        result = []
        for index, customer in enumerate(rows, start=start + 1):
            edit_url = reverse('staff:edit_customer', args=[customer.id])
            view_url = (
                f"{reverse('staff:view_customer_details')}?id={customer.latest_loan_id}"
                if customer.latest_loan_id else ''
            )
            result.append({
                'DT_RowIndex': index,
                'id': customer.id,
                'customer_name': customer.customer_name or '-',
                'phone_number': customer.phone_number or '-',
                'place': place_by_loan.get(customer.latest_loan_id, '-'),
                'total_chits': customer.total_chits,
                'edit_url': edit_url,
                'view_url': view_url,
            })

        return JsonResponse({
            'draw': draw,
            'recordsTotal': records_total,
            'recordsFiltered': records_filtered,
            'data': result,
        })

    except Exception:
        logger.exception('staff_view_all_customer failed')
        return JsonResponse({
            'draw': draw,
            'recordsTotal': 0,
            'recordsFiltered': 0,
            'data': [],
            'error': 'Could not load customers.',
        }, status=500)



def staff_update_customer(request, customer_id):
    logger.info(
        "Customer update started",
        extra={
            'method': request.method,
            'customer_id': customer_id
        }
    )

    # --------------------------------------------------
    # 1. GET CUSTOMER
    # --------------------------------------------------
    try:
        customer = staff_customers(request).get(id=customer_id)

    except Customer.DoesNotExist:
        logger.warning(
            "Customer not found",
            extra={'customer_id': customer_id}
        )

        if request.method == 'POST':
            return _json_error('Customer record not found.', 404)

        messages.error(request, "Customer record not found.")
        return redirect('staff:customer_management')

    except Exception:
        logger.exception(
            "Error while fetching customer",
            extra={'customer_id': customer_id}
        )

        if request.method == 'POST':
            return _json_error('Unable to fetch customer details.', 500)

        messages.error(request, "Unable to fetch customer details.")
        return redirect('staff:customer_management')

    # --------------------------------------------------
    # 2. GET REQUEST
    # --------------------------------------------------
    if request.method == 'GET':
        return render(
            request,
            'staffpanel/edit_customer.html',
            {'customer': customer}
        )

    # --------------------------------------------------
    # 3. METHOD VALIDATION
    # --------------------------------------------------
    if request.method != 'POST':
        logger.warning(
            "Invalid customer update request method",
            extra={
                'customer_id': customer_id,
                'method': request.method
            }
        )
        return _json_error('Invalid request method.', 405)

    # --------------------------------------------------
    # 4. FORM DATA AND VALIDATION
    # --------------------------------------------------
    try:
        data = _customer_form_data(request)
        aadhaar_photo = request.FILES.get('aadhaar_photo')

        errors = _validate_customer(
            data,
            aadhaar_photo,
            referral_required=False
        )

        if errors:
            logger.warning(
                "Customer update validation failed",
                extra={
                    'customer_id': customer_id,
                    'errors': errors
                }
            )
            return JsonResponse({
                'status': 'error',
                'message': 'Please correct the validation errors.',
                'errors': errors
            }, status=400)

        # --------------------------------------------------
        # 5. DATABASE TRANSACTION
        # --------------------------------------------------
        with transaction.atomic():

            # Lock the customer row during update
            customer = Customer.objects.select_for_update().get(
                id=customer_id
            )

            # Check duplicate Aadhaar number
            aadhaar_exists = Customer.objects.filter(
                aadhaar_number=data['aadhaar_number']
            ).exclude(
                pk=customer.pk
            ).exists()

            if aadhaar_exists:
                logger.warning(
                    "Duplicate Aadhaar number during customer update",
                    extra={'customer_id': customer_id}
                )

                return JsonResponse({
                    'status': 'error',
                    'message': 'This Aadhaar number belongs to another customer.',
                    'errors': {
                        'aadhaar_number': 'This Aadhaar number belongs to another customer.'
                    }
                }, status=400)

            # Update customer details
            customer.customer_name = data['customer_name']
            customer.phone_number = data['phone_number']
            customer.address = data['address']
            customer.aadhaar_number = data['aadhaar_number']
            customer.referral_name = data['referral_name'] or None
            customer.referral_phone = data['referral_phone'] or None

            # Replace photo only when a new photo is uploaded
            if aadhaar_photo:
                customer.aadhaar_photo = aadhaar_photo

            customer.save()

        # --------------------------------------------------
        # 6. SUCCESS RESPONSE
        # --------------------------------------------------
        logger.info(
            "Customer updated successfully",
            extra={'customer_id': customer.id}
        )

        return JsonResponse({
            'status': 'success',
            'message': 'Customer details updated successfully.',
            'redirect_url': reverse('staff:customer_management')
        })

    # --------------------------------------------------
    # 7. DATABASE INTEGRITY ERROR
    # --------------------------------------------------
    except IntegrityError:
        # transaction.atomic() automatically rolls back
        logger.exception(
            "Customer update database integrity error",
            extra={'customer_id': customer_id}
        )

        return _json_error(
            'Customer could not be updated due to a database constraint.',
            400
        )

    # --------------------------------------------------
    # 8. OTHER ERRORS
    # --------------------------------------------------
    except Exception:
        # transaction.atomic() automatically rolls back
        logger.exception(
            "Customer update failed",
            extra={'customer_id': customer_id}
        )

        return _json_error(
            'Customer could not be updated. Please try again.',
            500
        )
