"""
Complaint Templates UI views
"""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.translation import gettext_lazy as _

from apps.complaints.models import ComplaintTemplate, ComplaintCategory
from apps.organizations.models import Hospital, Department


@login_required
def template_list(request):
    """
    List all complaint templates
    """
    if not (request.user.is_px_admin() or request.user.is_hospital_admin()):
        messages.error(request, _("You don't have permission to manage templates."))
        return redirect('complaints:complaint_list')

    templates = ComplaintTemplate.objects.select_related('hospital', 'category', 'auto_assign_department').all()

    # Filter by hospital
    hospital_filter = request.GET.get('hospital')
    if hospital_filter:
        templates = templates.filter(hospital_id=hospital_filter)

    # Filter by active status
    is_active = request.GET.get('is_active')
    if is_active:
        templates = templates.filter(is_active=is_active == 'true')

    # Search
    search = request.GET.get('search')
    if search:
        templates = templates.filter(name_en__icontains=search)

    templates = templates.order_by('-usage_count', 'name_en')

    # Get hospitals for filter
    if request.user.is_px_admin():
        hospitals = Hospital.objects.filter(status='active').order_by('name')
    else:
        hospitals = Hospital.objects.filter(id=request.user.hospital_id) if request.user.hospital else []

    context = {
        'templates': templates,
        'hospitals': hospitals,
        'hospital_filter': hospital_filter,
        'is_active_filter': is_active,
        'search': search,
    }

    return render(request, 'complaints/templates/template_list.html', context)


@login_required
def template_create(request):
    """
    Create a new complaint template
    """
    if not (request.user.is_px_admin() or request.user.is_hospital_admin()):
        messages.error(request, _("You don't have permission to create templates."))
        return redirect('complaints:template_list')

    if request.method == 'POST':
        try:
            # Get hospital
            hospital_id = request.POST.get('hospital')
            hospital = get_object_or_404(Hospital, id=hospital_id)

            # Get category if provided
            category_id = request.POST.get('category')
            category = None
            if category_id:
                category = get_object_or_404(ComplaintCategory, id=category_id)

            # Get auto-assign department if provided
            auto_assign_dept_id = request.POST.get('auto_assign_department')
            auto_assign_department = None
            if auto_assign_dept_id:
                auto_assign_department = get_object_or_404(Department, id=auto_assign_dept_id)

            # Parse placeholders from JSON or empty list
            import json
            try:
                placeholders = json.loads(request.POST.get('placeholders', '[]'))
            except:
                placeholders = []

            template = ComplaintTemplate.objects.create(
                hospital=hospital,
                name=request.POST.get('name'),
                description=request.POST.get('description'),
                category=category,
                default_severity=request.POST.get('default_severity', 'medium'),
                default_priority=request.POST.get('default_priority', 'medium'),
                auto_assign_department=auto_assign_department,
                placeholders=placeholders,
                is_active=request.POST.get('is_active') == 'on',
            )

            messages.success(request, _("Template created successfully!"))
            return redirect('complaints:template_detail', pk=template.pk)

        except Exception as e:
            messages.error(request, _("Error creating template: {}").format(str(e)))

    # Get hospitals and categories for form
    if request.user.is_px_admin():
        hospitals = Hospital.objects.filter(status='active').order_by('name')
    else:
        hospitals = Hospital.objects.filter(id=request.user.hospital_id) if request.user.hospital else []

    categories = ComplaintCategory.objects.filter(level=2, is_active=True).order_by('name_en')[:50]

    context = {
        'hospitals': hospitals,
        'categories': categories,
        'template': None,
        'action': 'create',
    }

    return render(request, 'complaints/templates/template_form.html', context)


@login_required
def template_detail(request, pk):
    """
    View template details
    """
    template = get_object_or_404(
        ComplaintTemplate.objects.select_related('hospital', 'category', 'auto_assign_department'),
        pk=pk
    )

    context = {
        'template': template,
    }

    return render(request, 'complaints/templates/template_detail.html', context)


@login_required
def template_edit(request, pk):
    """
    Edit an existing template
    """
    if not (request.user.is_px_admin() or request.user.is_hospital_admin()):
        messages.error(request, _("You don't have permission to edit templates."))
        return redirect('complaints:template_detail', pk=pk)

    template = get_object_or_404(
        ComplaintTemplate.objects.select_related('hospital', 'category', 'auto_assign_department'),
        pk=pk
    )

    if request.method == 'POST':
        try:
            # Get hospital
            hospital_id = request.POST.get('hospital')
            template.hospital = get_object_or_404(Hospital, id=hospital_id)

            # Get category if provided
            category_id = request.POST.get('category')
            if category_id:
                template.category = get_object_or_404(ComplaintCategory, id=category_id)
            else:
                template.category = None

            # Get auto-assign department if provided
            auto_assign_dept_id = request.POST.get('auto_assign_department')
            if auto_assign_dept_id:
                template.auto_assign_department = get_object_or_404(Department, id=auto_assign_dept_id)
            else:
                template.auto_assign_department = None

            # Parse placeholders
            import json
            try:
                template.placeholders = json.loads(request.POST.get('placeholders', '[]'))
            except:
                template.placeholders = []

            template.name = request.POST.get('name')
            template.description = request.POST.get('description')
            template.default_severity = request.POST.get('default_severity', 'medium')
            template.default_priority = request.POST.get('default_priority', 'medium')
            template.is_active = request.POST.get('is_active') == 'on'
            template.save()

            messages.success(request, _("Template updated successfully!"))
            return redirect('complaints:template_detail', pk=template.pk)

        except Exception as e:
            messages.error(request, _("Error updating template: {}").format(str(e)))

    # Get hospitals and categories for form
    if request.user.is_px_admin():
        hospitals = Hospital.objects.filter(status='active').order_by('name')
    else:
        hospitals = Hospital.objects.filter(id=request.user.hospital_id) if request.user.hospital else []

    categories = ComplaintCategory.objects.filter(level=2, is_active=True).order_by('name_en')[:50]

    context = {
        'hospitals': hospitals,
        'categories': categories,
        'template': template,
        'action': 'edit',
    }

    return render(request, 'complaints/templates/template_form.html', context)


@login_required
def template_delete(request, pk):
    """
    Delete a template
    """
    if not request.user.is_px_admin():
        messages.error(request, _("You don't have permission to delete templates."))
        return redirect('complaints:template_detail', pk=pk)

    template = get_object_or_404(ComplaintTemplate, pk=pk)

    if request.method == 'POST':
        template_name = template.name
        template.delete()
        messages.success(request, _("Template '{}' deleted successfully!").format(template_name))
        return redirect('complaints:template_list')

    context = {
        'template': template,
    }

    return render(request, 'complaints/templates/template_confirm_delete.html', context)


@login_required
def template_toggle_status(request, pk):
    """
    Toggle template active status (AJAX)
    """
    if not (request.user.is_px_admin() or request.user.is_hospital_admin()):
        from django.http import JsonResponse
        return JsonResponse({'error': 'Permission denied'}, status=403)

    from django.http import JsonResponse

    if request.method != 'POST':
        return JsonResponse({'error': 'Method not allowed'}, status=405)

    template = get_object_or_404(ComplaintTemplate, pk=pk)
    template.is_active = not template.is_active
    template.save()

    return JsonResponse({
        'success': True,
        'is_active': template.is_active,
        'message': 'Template {} successfully'.format(
            'activated' if template.is_active else 'deactivated'
        )
    })
