from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
from django import forms
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from accounts.models import Profile
from accounts.forms import CustomerForm
from processes.utils import scope_customers_queryset
from common.consts import UserRoles
from common.decorators import allowed_roles


# Create your views here.
def login_view(request):
    """
    renders login page and authenticating user POST requests
    to log user in
    """
    # If already authenticated, go straight to request list
    if request.user.is_authenticated:
        return redirect("processes:request_list")
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect("processes:request_list")
        else:
            messages.error(request, "کاربری با این مشخصات یافت نشد!")
            return redirect("accounts:login")

    return render(request, "accounts/login.html")

def dashboard(request):
    return render(request, "accounts/dashboard.html")


@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def customer_list(request):
    # Get all profiles that have customer role
    base = Profile.objects.filter(roles__slug=UserRoles.CUSTOMER.value, is_deleted=False).select_related('user')
    customers = scope_customers_queryset(request.user, base)
    
    form = CustomerForm()
    return render(request, "accounts/customer_list.html", {
        "customers": customers,
        "form": form
    })


@require_POST
@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def add_customer_ajax(request):
    """AJAX endpoint for adding customers"""
    form = CustomerForm(request.POST, request.FILES)
    form.request = request  # Pass request to form
    if form.is_valid():
        try:
            customer = form.save()
            return JsonResponse({
                'success': True,
                'message': 'مشترک با موفقیت اضافه شد!',
                'customer': {
                    'id': customer.id,
                    'name': customer.user.get_full_name(),
                    'username': customer.user.username,
                    'phone': customer.phone_number_1 or 'ثبت نشده',
                    'national_code': customer.national_code or 'ثبت نشده',
                    'status': 'تکمیل شده' if customer.is_completed else 'ناقص'
                }
            })
        except forms.ValidationError as e:
            return JsonResponse({
                'success': False,
                'message': str(e)
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'خطا در ذخیره مشترک: {str(e)}'
            })
    else:
        return JsonResponse({
            'success': False,
            'message': 'خطا در اعتبارسنجی فرم',
            'errors': form.errors
        })


@require_POST
@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def edit_customer_ajax(request, customer_id):
    customer = get_object_or_404(Profile, id=customer_id)
    form = CustomerForm(request.POST, request.FILES, instance=customer)
    form.request = request  # Pass request to form
    if form.is_valid():
        try:
            customer = form.save()
            return JsonResponse({
                'success': True,
                'message': 'مشترک با موفقیت ویرایش شد!',
                'customer': {
                    'id': customer.id,
                    'name': customer.user.get_full_name(),
                    'username': customer.user.username,
                    'phone': customer.phone_number_1 or 'ثبت نشده',
                    'national_code': customer.national_code or 'ثبت نشده',
                    'status': 'تکمیل شده' if customer.is_completed else 'ناقص'
                }
            })
        except forms.ValidationError as e:
            return JsonResponse({
                'success': False,
                'message': str(e)
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'خطا در ویرایش مشترک: {str(e)}'
            })
    else:
        return JsonResponse({
            'success': False,
            'message': 'خطا در اعتبارسنجی فرم',
            'errors': form.errors
        })

@require_GET
@login_required
def get_customer_data(request, customer_id):
    customer = get_object_or_404(Profile, id=customer_id)
    
    # Create form with existing customer data
    form = CustomerForm(instance=customer, initial={
        'first_name': customer.user.first_name,
        'last_name': customer.user.last_name,
    })
    
    # Render form fields as HTML
    form_html = {
        'first_name': str(form['first_name']),
        'last_name': str(form['last_name']),
        'user_type': str(form['user_type']),
        'phone_number_1': str(form['phone_number_1']),
        'phone_number_2': str(form['phone_number_2']),
        'national_code': str(form['national_code']),
        'company_name': str(form['company_name']),
        'company_national_id': str(form['company_national_id']),
        'card_number': str(form['card_number']),
        'account_number': str(form['account_number']),
        'address': str(form['address']),
        'bank_name': str(form['bank_name']),
    }
    
    return JsonResponse({
        'success': True,
        'customer': {
            'id': customer.id,
            'first_name': customer.user.first_name,
            'last_name': customer.user.last_name,
            'user_type': customer.user_type or 'individual',
            'phone_number_1': customer.phone_number_1 or '',
            'phone_number_2': customer.phone_number_2 or '',
            'national_code': customer.national_code or '',
            'company_name': customer.company_name or '',
            'company_national_id': customer.company_national_id or '',
            'card_number': customer.card_number or '',
            'account_number': customer.account_number or '',
            'address': customer.address or '',
            'bank_name': customer.bank_name or '',
        },
        'form_html': form_html
    })


@require_GET
@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def get_customer_details(request, customer_id):
    """جزئیات کامل مشترک برای نمایش در مدال"""
    customer = get_object_or_404(
        Profile.objects.select_related('user', 'affairs', 'county', 'broker'),
        id=customer_id
    )

    data = {
        'id': customer.id,
        'user': {
            'username': customer.user.username,
            'first_name': customer.user.first_name or '',
            'last_name': customer.user.last_name or '',
            'full_name': customer.user.get_full_name() or customer.user.username,
            'email': customer.user.email or '',
            'date_joined': customer.jcreated_date() if customer.user.date_joined else '',
        },
        'national_code': customer.national_code or '',
        'user_type': customer.user_type or 'individual',
        'company_name': customer.company_name or '',
        'company_national_id': customer.company_national_id or '',
        'phone_number_1': customer.phone_number_1 or '',
        'phone_number_2': customer.phone_number_2 or '',
        'card_number': customer.card_number or '',
        'account_number': customer.account_number or '',
        'bank_name': customer.get_bank_name_display() or '',
        'address': customer.address or '',
        'pic_url': customer.pic.url if customer.pic else '',
        'affairs': str(customer.affairs) if customer.affairs else '',
        'county': str(customer.county) if customer.county else '',
        'broker': str(customer.broker) if customer.broker else '',
        'is_completed': customer.is_completed,
    }

    # تعداد چاه‌ها و درخواست‌ها برای نمایش سریع
    try:
        from wells.models import Well
        from processes.models import ProcessInstance
        total_wells = Well.objects.filter(representative=customer.user, is_deleted=False).count()
        total_requests = ProcessInstance.objects.filter(representative=customer.user, is_deleted=False).count()
    except Exception:
        total_wells = 0
        total_requests = 0

    return JsonResponse({
        'success': True, 
        'customer': data, 
        'total_wells': total_wells,
        'total_requests': total_requests
    })


@require_GET
@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def get_customer_wells(request, customer_id):
    """چاه‌های مرتبط با یک مشترک"""
    customer = get_object_or_404(Profile, id=customer_id)
    
    try:
        from wells.models import Well
        qs = Well.objects.select_related(
            'water_meter_manufacturer', 'affairs', 'county', 'broker'
        ).filter(representative=customer.user, is_deleted=False).order_by('-created')
        
        items = []
        for well in qs[:100]:  # محدودسازی برای عملکرد
            items.append({
                'id': well.id,
                'water_subscription_number': well.water_subscription_number,
                'electricity_subscription_number': well.electricity_subscription_number or '',
                'water_meter_serial_number': well.water_meter_serial_number or '',
                'water_meter_manufacturer': str(well.water_meter_manufacturer) if well.water_meter_manufacturer else '',
                'well_power': well.well_power or '',
                'affairs': str(well.affairs) if well.affairs else '',
                'county': str(well.county) if well.county else '',
                'broker': str(well.broker) if well.broker else '',
                'created': well.jcreated_date() if hasattr(well, 'created') and well.created else '',
            })
    except Exception:
        items = []

    return JsonResponse({'success': True, 'wells': items})


@require_GET
@login_required
@allowed_roles([UserRoles.ADMIN, UserRoles.BROKER, UserRoles.MANAGER, UserRoles.ACCOUNTANT, UserRoles.WATER_RESOURCE_MANAGER])
def get_customer_requests(request, customer_id):
    """درخواست‌های مرتبط با یک مشترک"""
    customer = get_object_or_404(Profile, id=customer_id)
    
    try:
        from processes.models import ProcessInstance
        qs = ProcessInstance.objects.select_related(
            'process', 'current_step', 'requester', 'well'
        ).filter(representative=customer.user, is_deleted=False).order_by('-created')
        
        items = []
        for inst in qs[:100]:  # محدودسازی برای عملکرد
            try:
                url = reverse('processes:instance_summary', args=[inst.id]) if inst.status == 'completed' else reverse('processes:instance_steps', args=[inst.id])
            except Exception:
                url = ''
            items.append({
                'id': inst.id,
                'code': inst.code,
                'process': inst.process.name if inst.process else '',
                'status': inst.status,
                'status_display': inst.get_status_display(),
                'current_step': inst.current_step.name if inst.current_step else '',
                'requester': inst.requester.get_full_name() if inst.requester else '',
                'well_subscription': inst.well.water_subscription_number if inst.well else '',
                'created': inst.jcreated_date() if hasattr(inst, 'created') and inst.created else '',
                'url': url,
            })
    except Exception:
        items = []

    return JsonResponse({'success': True, 'requests': items})


@login_required
def logout_view(request):
    """Log out current user and redirect to login page."""
    logout(request)
    return redirect("accounts:login")
