import datetime
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.views import generic
from django_datatables_view.base_datatable_view import BaseDatatableView

from module_iam import iam_constant, permission
from module_iam.models import IAmPrincipal
from module_project import constants
from module_project.mixins import ActionMixin, DatatablesMixin
from module_project.service import EmailService
from module_project.utils import JsonResponseUtil

from .models import ContactUs, Feedback

# Create your views here.


class ContactUsView(LoginRequiredMixin, permission.ResourcePermissionRequiredMixin, generic.TemplateView):
    page_name = iam_constant.RESOURCE_MANAGE_CONTACT_US
    resource = iam_constant.RESOURCE_MANAGE_CONTACT_US
    action = None
    template_name = "module_support/contact_us.html"
    model = ContactUs
    context_objext_name = "obj"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class ContactUsListJson(BaseDatatableView):
    model = ContactUs
    columns = ["id", "email_address", "subject", "message", "reply", "active"]
    order_columns = ["id", "email_address", "subject", "message", "reply", "active"]

    FILTER_ICONTAINS = "icontains"

    def get_filter_method(self):
        """Returns preferred filter method"""
        return self.FILTER_ICONTAINS

    def get_initial_queryset(self):
        deleted_flag = self.request.GET.get('deleted_flag', None)

        return self.model.objects.filter(deleted=deleted_flag)

    def filter_queryset(self, qs):
        print(f"request is {self.request.GET}")
        search_value = self.request.GET.get("search[value]", None)
        if search_value:
            qs = super().filter_queryset(qs)  # Call the built-in filtering first

        for column in self.columns:
            print(f" columen index pattern {self.request.GET.get(f'columns[{self.columns.index(column)+1}][search][value]', None)}")
            search_value = self.request.GET.get(f'columns[{self.columns.index(column)+1}][search][value]', None)
            if search_value:
                column_data = self.request.GET.get(f'columns[{self.columns.index(column)+1}][data]')
                if column_data == "active":
                    qs = qs.filter(**{f"{column}": search_value})
                else:
                    qs = qs.filter(**{f"{column}__icontains": search_value})

        return qs
    
    def ordering(self, qs):
        order = self.request.GET.get('order[0][dir]', None)
        if order:
            column_index = int(self.request.GET.get('order[0][column]', None)) - 1
            order_column = self.order_columns[column_index]

            if order == "asc":
                qs = qs.order_by(order_column)
            elif order == "desc":
                qs = qs.order_by("-" + order_column)

        return qs


class ContactUsActionView(ActionMixin):
    model = ContactUs

class ContactUsArchiveView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.TemplateView):
    page_name = iam_constant.RESOURCE_MANAGE_CONTACT_US
    resource = iam_constant.RESOURCE_MANAGE_CONTACT_US
    action = None
    template_name = "module_support/contactus_archive_list.html"
    model = ContactUs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context

class ContactUsReplyView(LoginRequiredMixin, generic.View):
    page_name = iam_constant.RESOURCE_MANAGE_CONTACT_US
    model = ContactUs
    success_message = constants.DATA_SAVED

    def post(self, request, *args, **kwargs):
        id = self.kwargs.get("id")
        message = request.POST.get("message")
        print(f"id and message is {id} {message}")
        if id and message:
            try:
                instance = self.model.objects.get(id=id)
                instance.reply = message
                instance.save()

                email_service = EmailService(
                    subject=f"Reply  of your inquiry - {instance.subject}",
                    to=instance.email_address,
                    from_email=settings.EMAIL_HOST_USER,
                )
                email_service.set_text_body(message)
                email_service.send()
                print(f"email service is {email_service}")
                return JsonResponseUtil.success(message=self.success_message)
            except self.model.DoesNotExist:
                return JsonResponseUtil.error(message=constants.FAILURE, errors="Invalid contact us ID.")
            except Exception as e:
                return JsonResponseUtil.error(message=constants.FAILURE, errors=str(e))
        else:
            return JsonResponseUtil.error(message=constants.FAILURE, errors="Missing 'id' or 'message' in the request")

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ContactUsLandingView(request):
    name = request.POST.get('full_name')
    email = request.POST.get('email')
    subject = request.POST.get('subject')
    message = request.POST.get('message')

    if not all([name, email, subject, message]):
        return JsonResponseUtil.error(message=constants.FAILURE, errors='Please fill in all the fields.')

    try:
        contact_us = ContactUs(
            name=name,
            email_address=email,
            subject=subject,
            message=message
        )
        contact_us.save()

        context = {
            "name": name,
            "email": email,
            "subject": subject,
            "message": message,
            "year": datetime.datetime.year
        }
        print(context)

        # Send the email to support team
        support_team_service = EmailService(
            subject=f"New contact us - {subject}",
            to=email,
            from_email=settings.EMAIL_HOST_USER,
        )

        support_team_service.load_template(
            "module_support/contact_us_support.html", context=context
        )
        support_team_service.send()

        # Send the email to support team
        thankyou_service = EmailService(
            subject=f"New contact us - {subject}",
            to=email,
            from_email=settings.EMAIL_HOST_USER,
        )

        thankyou_service.load_template(
            "module_support/thank_you_support.html", context=context
        )
        thankyou_service.send()

    except Exception as e:
        print(f"Error occur in ContactUsLandingView {str(e)}")
        return JsonResponseUtil.error(message=constants.FAILURE, errors=constants.SOMETHING_WRONG)

    return JsonResponseUtil.success(message='Thank you for contacting us!')


class FeedbackView(permission.ResourcePermissionRequiredMixin, LoginRequiredMixin, generic.TemplateView):
    page_name = iam_constant.RESOURCE_MANAGE_FEEDBACK
    resource = iam_constant.RESOURCE_MANAGE_FEEDBACK
    action = None
    template_name = "module_support/feedback.html"
    model = Feedback
    context_objext_name = "obj"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["page_name"] = self.page_name
        return context


class FeedbackListJson(BaseDatatableView):
    model = Feedback
    columns = ["id", "principal.email", "feedback_reaction", "comment", "active"]
    order_columns = ["id", "principal.email", "feedback_reaction", "comment", "active"]

    def get_initial_queryset(self):
        deleted_flag = self.request.GET.get('deleted_flag', None)

        return self.model.objects.filter(deleted=deleted_flag)

    def filter_queryset(self, qs):
        # Implement your custom filtering logic here
        print(f"request is {self.request.GET}")
        search_value = self.request.GET.get("search[value]", None)
        if search_value:
            qs = qs.filter(
                Q(id__icontains=search_value)
                | Q(feedback_reaction__icontains=search_value)
                | Q(principal__email__icontains=search_value)
                | Q(comment__icontains=search_value)
            )
        return qs


class FeedbackActionView(ActionMixin):
    model = Feedback
    pass
