import logging
import re
from django.contrib.auth.hashers import make_password
from django.db import transaction, IntegrityError
from django.shortcuts import redirect
from django.contrib import messages
from datetime import datetime
from django.http import JsonResponse
from decimal import Decimal, InvalidOperation
from NexusApp.utils.crypto import encrypt_password, decrypt_password
from NexusApp.models import AdminUser, Staff, Loan, Place, LoanPayment, Customer
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from django.urls import reverse
from django.utils.html import escape
from django.views.decorators.http import require_POST
from django.db.models import Sum

logger = logging.getLogger(__name__)



def login(request):
    return render(request, 'adminpanel/login.html')

def forgot_password(request):
    return render(request, 'adminpanel/forgot_password.html')

def new_password(request):
    return render(request, 'adminpanel/new_password.html')

def reset_password(request):
    return render(request, 'adminpanel/reset_password.html')

def _inr(value):
    """12345678.5 -> '1,23,45,679' (Indian digit grouping, no decimals)."""
    n = int(Decimal(str(value or 0)).quantize(Decimal('1')))
    sign = '-' if n < 0 else ''
    s = str(abs(n))
    if len(s) > 3:
        head, tail = s[:-3], s[-3:]
        head = re.sub(r'(\d)(?=(\d\d)+$)', r'\1,', head)
        s = head + ',' + tail
    return sign + s


def dashboard(request):
    from datetime import timedelta
    from django.utils import timezone
    from NexusApp.utils.loan_stats import portfolio_summary

    today = timezone.localdate()
    month_start = today.replace(day=1)

    loans = Loan.objects.all()
    summary = portfolio_summary(loans, today)

    customers_with_loans = Customer.objects.filter(loans__isnull=False).distinct()
    total_customers = customers_with_loans.count()
    active_customers = Customer.objects.filter(loans__status='active').distinct().count()
    new_customers_month = Customer.objects.filter(created_at__date__gte=month_start).count()

    total_given = loans.aggregate(t=Sum('loan_amount'))['t'] or Decimal('0')
    given_today = loans.filter(loan_date=today).aggregate(t=Sum('loan_amount'))['t'] or Decimal('0')
    given_month = loans.filter(loan_date__gte=month_start).aggregate(t=Sum('loan_amount'))['t'] or Decimal('0')

    payments = LoanPayment.objects.all()
    total_received = payments.aggregate(t=Sum('amount'))['t'] or Decimal('0')
    received_today = payments.filter(payment_date=today).aggregate(t=Sum('amount'))['t'] or Decimal('0')
    received_month = payments.filter(payment_date__gte=month_start).aggregate(t=Sum('amount'))['t'] or Decimal('0')

    pending = max(summary['payable'] - total_received, Decimal('0'))
    pct = lambda part, whole: int(round(part * 100 / whole)) if whole else 0

    # loans paid today out of (paid today + still due today / overdue)
    paid_today_loans = payments.filter(payment_date=today).values('loan_id').distinct().count()
    base = paid_today_loans + summary['due_today'] + summary['overdue_loans']

    recent = [{
        'id': p.id,
        'customer_name': p.loan.customer.customer_name,
        'amount': float(p.amount),
        'staff': p.collected_by.name if p.collected_by else 'Admin',
        'url': f"{reverse('admin:paid_due_history')}?id={p.loan_id}",
    } for p in payments.filter(payment_date=today)
        .select_related('loan__customer', 'collected_by').order_by('-id')[:50]]

    return render(request, 'adminpanel/dashboard.html', {
        'total_customers': total_customers,
        'active_customers': active_customers,
        'inactive_customers': max(total_customers - active_customers, 0),
        'new_customers_month': new_customers_month,
        'total_amount_given': _inr(total_given),
        'given_today': _inr(given_today),
        'given_month_pct': pct(given_month, total_given),
        'total_amount_received': _inr(total_received),
        'received_today': _inr(received_today),
        'received_month_pct': pct(received_month, total_received),
        'total_pending_amount': _inr(pending),
        'pending_pct': pct(pending, summary['payable']),
        'due_today_count': summary['due_today'],
        'overdue_customers': summary['overdue_customers'],
        'overdue_loans': summary['overdue_loans'],
        'overdue_amount': _inr(summary['overdue_amount']),
        'new_loans_month': loans.filter(loan_date__gte=month_start).count(),
        'due_this_week': summary['due_today'] + summary['upcoming_dues'],
        'collection_progress': min(pct(paid_today_loans, base), 100),
        'recovery_rate': min(summary['recovery_rate'], 100),
        'recent_collections': recent,
    })

# CUSTOMER MANAGEMENT

def customer_management(request):
    return render(request, 'adminpanel/customer_management.html')

def payment_history(request):
    loan_id = request.GET.get('id', '').strip()
    if loan_id.isdigit():
        return redirect(f"{reverse('admin:paid_due_history')}?id={loan_id}")
    return redirect('admin:customer_management')

# LOAN MANAGEMENT

def loan_dashboard(request):
    # there is no separate loan dashboard page; Loan Registers is the loan home
    return redirect('admin:loan_registers')

def add_loan(request):
    # suggestions for the place / referral inputs come from real data
    places = list(Place.objects.values_list('name', flat=True))
    referral_names = list(
        Customer.objects.exclude(referral_name__isnull=True)
        .exclude(referral_name='')
        .order_by('referral_name')
        .values_list('referral_name', flat=True)
        .distinct()
    )
    return render(request, 'adminpanel/add_loan.html', {
        'places': places,
        'referral_names': referral_names,
    })

def loan_reports(request, place_id=None):
    # /admin/loan_reports/            -> every place
    # /admin/loan_reports/<place_id>/ -> one place
    place_name = ''
    if place_id is not None:
        place_name = get_object_or_404(Place, pk=place_id).name
    return render(request, 'adminpanel/loan_reports.html', {'place_name': place_name})

def view_loan_report(request):
    # detail pages all show the same real loan view (summary + payments)
    loan_id = request.GET.get('id', '').strip()
    if loan_id.isdigit():
        return redirect('admin:view_place_loan', loan_id=int(loan_id))
    return redirect('admin:loan_registers')

def loan_registers(request):
    return render(request, 'adminpanel/loan_registers.html')

def loan_entries(request):
    return render(request, 'adminpanel/loan_entries.html')


def reports(request):
    return render(request, 'adminpanel/reports.html')

def view_loan_entry(request):
    # detail pages all show the same real loan view (summary + payments)
    loan_id = request.GET.get('id', '').strip()
    if loan_id.isdigit():
        return redirect('admin:view_place_loan', loan_id=int(loan_id))
    return redirect('admin:loan_registers')

def view_customer_details(request, loan_id=None):
    # The customer list links here with the customer's latest loan id.
    if loan_id is None:
        return redirect('admin:customer_management')

    selected = Loan.objects.select_related('customer', 'place').filter(id=loan_id).first()
    if selected is None:
        messages.error(request, "Customer record not found.")
        return redirect('admin:customer_management')

    customer = selected.customer
    loans = customer.loans.select_related('place').order_by('-id')
    customer.place = selected.place.name          # latest place, shown in the header

    aadhaar = customer.aadhaar_number or ''
    masked_aadhaar = ('XXXX XXXX ' + aadhaar[-4:]) if len(aadhaar) == 12 else '-'

    return render(request, 'adminpanel/view_customer_details.html', {
        'customer': customer,
        'loans': loans,
        'total_loans': loans.count(),
        'masked_aadhaar': masked_aadhaar,
        'aadhaar_photo_url': customer.aadhaar_photo.url if customer.aadhaar_photo else '',
    })

def paid_due_history(request):
    return render(request, 'adminpanel/paid_due_history.html')

def completed_loan(request):
    return render(request, 'adminpanel/completed_loan.html')

def view_completed_loan(request):
    # detail pages all show the same real loan view (summary + payments)
    loan_id = request.GET.get('id', '').strip()
    if loan_id.isdigit():
        return redirect('admin:view_place_loan', loan_id=int(loan_id))
    return redirect('admin:loan_registers')

def place_completed_loan(request, place_id=None):
    if place_id is None:
        return redirect('admin:loan_registers')
    place = get_object_or_404(Place, pk=place_id)
    return render(request, 'adminpanel/place_completed_loan.html',
                  {'place': place.name, 'place_id': place.id})

def view_place_loan(request, loan_id=None):
    if loan_id is None:
        return redirect('admin:loan_registers')
    loan = get_object_or_404(Loan.objects.select_related('place'), pk=loan_id)
    payments = [
        {
            'sno': i,
            'payment_date': p.payment_date.isoformat(),
            'amount': float(p.amount),
            'payment_method': p.get_payment_method_display(),
        }
        for i, p in enumerate(loan.payments.all(), start=1)
    ]
    return render(request, 'adminpanel/view_place_loan.html', {
        'loan': loan,
        'place_name': loan.place.name,
        'payments': payments,
    })

def overdue_loan(request):
    return render(request, 'adminpanel/overdue_loan.html')

def today_collections(request):
    return render(request, 'adminpanel/today_collections.html')

def collection_list(request):
    return render(request, 'adminpanel/collection_list.html')

def active_loan(request):
    return render(request, 'adminpanel/active_loan.html')

def view_active_loan(request):
    return render(request, 'adminpanel/view_active_loan.html')


def view_loan(request):
    return render(request, 'adminpanel/view_loan.html')

def edit_loan(request):
    return render(request, 'adminpanel/edit_loan.html')

def loan_request(request):
    return render(request, 'adminpanel/loan_request.html')

def view_loan_request(request):
    return render(request, 'adminpanel/view_loan_request.html')
# PAYMENT MANAGEMENT



# STAFF MANAGEMENT 

def add_staff(request):
    # 1. Automatically calculate the next sequential ID
    last_staff = Staff.objects.all().order_by('id').last()
    if not last_staff or not last_staff.employee_id:
        next_id = "EMP001"
    else:
        try:
            last_num = int(last_staff.employee_id.replace('EMP', ''))
            next_id = f"EMP{last_num + 1:03d}"
        except ValueError:
            next_id = "EMP001"

    # 2. Pass it inside the context dictionary
    context = {
        'next_employee_id': next_id,
        'places': Place.objects.order_by('name'),
        'assigned_place_ids': [],
    }
    
    # 3. Render your HTML form page
    return render(request, 'adminpanel/add_staff.html', context)

def staff_list(request):
    return render(request, 'adminpanel/staff_list.html')

def edit_staff(request, staff_id):
    try:
        staff = Staff.objects.get(id=staff_id)
    except Staff.DoesNotExist:
        messages.error(request, "Staff not found.")
        return redirect('admin:staff_list')
    return render(request, 'adminpanel/edit_staff.html', {
        'staff': staff,
        'places': Place.objects.order_by('name'),
        'assigned_place_ids': list(staff.places.values_list('id', flat=True)),
    })

def staff_collection_details(request):
    staff_id = request.GET.get('id', '').strip()
    try:
        staff = Staff.objects.get(id=staff_id)
    except (Staff.DoesNotExist, ValueError):
        messages.error(request, "Staff not found.")
        return redirect('admin:staff_list')
    return render(request, 'adminpanel/staff_collection_details.html', {'staff': staff})

def staff_attendence(request):
    from controllers.Admin.AdminattendanceController import admin_attendance_summary
    summary = admin_attendance_summary(request)
    return render(request, 'adminpanel/staff_attendence.html', {
        'total_staff': summary['total_staff'],
        'present_today': summary['present'],
        'absent_today': summary['absent'],
        'late_today': summary['late'],
    })

def add_lead(request):
    return render(request, 'adminpanel/add_lead.html')


def payment_invoice(request):
    return render(request, 'adminpanel/payment_invoice.html')


def set_attendance(request):
    from NexusApp.models import AttendanceMaster
    m = AttendanceMaster.objects.filter(is_active=True).first()
    current = None
    if m:
        current = {
            'start_time': m.start_time.strftime('%H:%M'), 'end_time': m.end_time.strftime('%H:%M'),
            'late_grace_minutes': m.late_grace_minutes, 'allowed_break_minutes': m.allowed_break_minutes,
            'working_days': m.working_days or [],
            'permission_hours_per_month': m.permission_hours_per_month,
            'max_permissions_per_month': m.max_permissions_per_month,
            'permission_is_paid': m.permission_is_paid, 'deduct_excess_permission': m.deduct_excess_permission,
            'salary_cycle_start_day': m.salary_cycle_start_day, 'salary_cycle_end_day': m.salary_cycle_end_day,
            'salary_payment_day': m.salary_payment_day or '',
            'km_allowance_enabled': m.km_allowance_enabled, 'km_rate': str(m.km_rate or ''),
            'paid_leave_enabled': m.paid_leave_enabled,
            'paid_leave_days_per_month': m.paid_leave_days_per_month,
            'paid_leave_days_per_year': m.paid_leave_days_per_year,
            'is_active': m.is_active,
        }
    return render(request, 'adminpanel/set_attendance.html', {'current_master': current})