import logging
import re
from datetime import datetime
from decimal import Decimal

from django.contrib import messages
from django.db import IntegrityError, transaction
from django.db.models import Count, Max, Q
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.decorators.http import require_POST
from PIL import Image

from NexusApp.models import Customer, Loan, Place

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Limits. They mirror the model fields so bad input is rejected with a clear
# message instead of failing in the database:
#   Place.name 150 | Customer.customer_name 200 | Customer.address 200
#   Customer.referral_name 150 | Loan.loan_amount / due_amount max_digits=12
#   Loan.total_payable max_digits=14 (2 decimals)
# ---------------------------------------------------------------------------
MAX_PLACE = 150
MAX_NAME = 200
MAX_ADDRESS = 200
MAX_REFERRAL_NAME = 150
MAX_NOTES = 255
MAX_PHOTO_BYTES = 2 * 1024 * 1024
ALLOWED_PHOTO_EXT = {'jpg', 'jpeg', 'png'}
ALLOWED_PHOTO_FORMATS = {'JPEG', 'PNG'}
MONEY_LIMIT = Decimal('10000000000')        # loan_amount / due_amount < 10^10
TOTAL_LIMIT = Decimal('1000000000000')      # total_payable < 10^12


# ----------------------------- helpers ------------------------------------
def _json_error(message, status=400):
    return JsonResponse({'status': 'error', 'message': message}, status=status)


def _parse_date(value):
    try:
        return datetime.strptime(value, '%Y-%m-%d').date()
    except (TypeError, ValueError):
        return None


def _parse_money(value):
    """'1500' or '1500.50' -> Decimal, anything else -> None."""
    if not re.fullmatch(r'[0-9]+(\.[0-9]{1,2})?', value or ''):
        return None
    amount = Decimal(value)
    if amount <= 0 or amount >= MONEY_LIMIT:
        return None
    return amount


def _check_photo(photo):
    """Return an error message for a bad Aadhaar photo, or None when it is fine."""
    ext = photo.name.rsplit('.', 1)[-1].lower() if '.' in photo.name else ''
    if ext not in ALLOWED_PHOTO_EXT:
        return "Only JPG, JPEG and PNG images are allowed."
    if photo.size > MAX_PHOTO_BYTES:
        return "Photo must not exceed 2 MB."
    # Do not trust the extension / browser content-type: open the file.
    try:
        image = Image.open(photo)
        image.verify()
        image_format = image.format
    except Exception:
        return "Invalid image file."
    finally:
        photo.seek(0)
    if image_format not in ALLOWED_PHOTO_FORMATS:
        return "Only JPG, JPEG and PNG images are allowed."
    return None


def _validate_customer(data, photo, referral_required):
    """Validation shared by add-loan and edit-customer."""
    errors = {}

    if not data['phone_number']:
        errors['phone_number'] = "Phone number is required."
    elif not re.fullmatch(r'[0-9]{10}', data['phone_number']):
        errors['phone_number'] = "Enter a valid 10-digit phone number."

    if not data['customer_name']:
        errors['customer_name'] = "Customer name is required."
    elif len(data['customer_name']) > MAX_NAME:
        errors['customer_name'] = f"Customer name cannot exceed {MAX_NAME} characters."

    if not data['address']:
        errors['address'] = "Address is required."
    elif len(data['address']) > MAX_ADDRESS:
        errors['address'] = f"Address cannot exceed {MAX_ADDRESS} characters."

    if not data['aadhaar_number']:
        errors['aadhaar_number'] = "Aadhaar number is required."
    elif not re.fullmatch(r'[0-9]{12}', data['aadhaar_number']):
        errors['aadhaar_number'] = "Aadhaar number must be exactly 12 digits."

    if photo:
        photo_error = _check_photo(photo)
        if photo_error:
            errors['aadhaar_photo'] = photo_error

    if not data['referral_name']:
        if referral_required:
            errors['referral_name'] = "Referral name is required."
    elif len(data['referral_name']) > MAX_REFERRAL_NAME:
        errors['referral_name'] = f"Referral name cannot exceed {MAX_REFERRAL_NAME} characters."

    if not data['referral_phone']:
        if referral_required:
            errors['referral_phone'] = "Referral phone number is required."
    elif not re.fullmatch(r'[0-9]{10}', data['referral_phone']):
        errors['referral_phone'] = "Enter a valid 10-digit referral phone number."

    return errors


def _customer_form_data(request):
    post = request.POST
    return {
        'phone_number': post.get('phone_number', '').strip(),
        'customer_name': post.get('customer_name', '').strip(),
        'address': post.get('address', '').strip(),
        'aadhaar_number': post.get('aadhaar_number', '').strip(),
        'referral_name': post.get('referral_name', '').strip(),
        'referral_phone': post.get('referral_phone', '').strip(),
    }


# ----------------------------- add loan -----------------------------------
def 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')

    # collapse repeated spaces so "Nagercoil" and "Nagercoil  " are one place
    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:
        # place must be one of the places added in Loan Registers -> Add Place
        place_obj = Place.objects.filter(name__iexact=place).first()
        if place_obj is None:
            errors['place'] = "Select a place from the list (add new places in Loan Registers)."

    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."

    # Loan.save() stores due_amount * number_of_dues in total_payable
    # (DecimalField max_digits=14), so make sure it fits.
    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 and refresh its details,
            # otherwise create it. The loan itself only stores the FK.
            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:                      # keep the old photo if none uploaded
                customer.aadhaar_photo = aadhaar_photo
            customer.save()

            loan = Loan.objects.create(
                customer=customer,
                place=place_obj,
                staff=None,                        # added by an admin, not a staff member
                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('admin: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 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)

    # Place belongs to the loan, not the customer: suggest the latest loan's place.
    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 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 = Customer.objects.all()
        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=Loan.objects.filter(
                    place__name__icontains=search).values('customer_id'))
            )
        records_filtered = customers.count()

        customers = customers.annotate(
            total_chits=Count('loans'),
            latest_loan_id=Max('loans__id'),
        )

        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):
            # view_customer_details (admin_views) is still keyed on a loan id
            view_url = (
                reverse('view_customerDetails', args=[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': reverse('edit_customer', args=[customer.id]),
                'view_url': view_url,
            })

        return JsonResponse({
            'draw': draw,
            'recordsTotal': records_total,
            'recordsFiltered': records_filtered,
            'data': result,
        })

    except Exception:
        logger.exception('view_all_customer failed')
        return JsonResponse({
            'draw': draw,
            'recordsTotal': 0,
            'recordsFiltered': 0,
            'data': [],
            'error': 'Could not load customers.',
        }, status=500)


# ----------------------------- edit customer -------------------------------
def update_customer(request, customer_id):
    logger.info("Customer update started",
                extra={'method': request.method, 'customer_id': customer_id})

    try:
        customer = Customer.objects.get(id=customer_id)
    except Customer.DoesNotExist:
        if request.method == 'POST':
            return _json_error('Customer record not found.', 404)
        messages.error(request, "Customer record not found.")
        return redirect('customer_management')

    if request.method == 'GET':
        return render(request, 'adminpanel/edit_customer.html', {'customer': customer})

    if request.method != 'POST':
        return _json_error('Invalid request method.', 405)

    data = _customer_form_data(request)
    aadhaar_photo = request.FILES.get('aadhaar_photo')

    errors = _validate_customer(data, aadhaar_photo, referral_required=False)

    if 'aadhaar_number' not in errors and Customer.objects.filter(
            aadhaar_number=data['aadhaar_number']).exclude(pk=customer.pk).exists():
        errors['aadhaar_number'] = "This Aadhaar number belongs to another customer."

    if errors:
        logger.warning("Customer update validation failed",
                       extra={'customer_id': customer_id, 'errors': errors})
        return JsonResponse({'status': 'error', 'errors': errors}, status=400)

    try:
        with transaction.atomic():
            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
            if aadhaar_photo:                      # replace photo only if a new one is sent
                customer.aadhaar_photo = aadhaar_photo
            customer.save()

        logger.info("Customer updated successfully", extra={'customer_id': customer.id})
        return JsonResponse({
            'status': 'success',
            'message': 'Customer details updated successfully.',
            'redirect_url': reverse('admin:customer_management'),
        })

    except IntegrityError:
        logger.exception("Customer update database integrity error")
        return _json_error('Customer could not be updated due to a database constraint.')
    except Exception:
        logger.exception("Customer update failed")
        return _json_error('Customer could not be updated. Please try again.', 500)


# ----------------------------- delete customer -----------------------------
@require_POST
def delete_customer(request):
    customer_id = request.POST.get('id', '').strip()

    if not customer_id.isdigit():
        messages.error(request, "Customer ID is required.")
        return redirect('customer_management')

    try:
        with transaction.atomic():
            customer = Customer.objects.filter(id=customer_id).first()
            if customer is None:
                messages.error(request, "Customer record not found.")
                return redirect('customer_management')

            # Loan.customer is PROTECT, so remove the loans first
            # (their payments are removed by CASCADE), then the customer.
            customer.loans.all().delete()
            customer.delete()

        messages.success(request, "Customer and all loan records deleted successfully.")

    except Exception:
        logger.exception("Customer deletion failed")
        messages.error(request, "Unable to delete customer.")

    return redirect('customer_management')