from django.contrib.auth import get_user_model
from django.contrib.auth.views import LoginView
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView, FormView, ListView, UpdateView

from accounts.forms import LoginForm, RegisterForm
from accounts.models import DepotUser

from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.mixins import AccessMixin
# Create your views here.


class DepotLoginView(LoginView):
    template_name = 'registration/login.html'
    # success_url = reverse_lazy('dashboard')
    form_class = LoginForm
    next_page = reverse_lazy('dashboard')


def is_company_admin(user):
    return user.is_authenticated and user.is_company_admin

@method_decorator(login_required, name='dispatch')
class RegisterView(AccessMixin, FormView):
    template_name = 'registration/register.html'
    form_class = RegisterForm
    # model = get_user_model()
    success_url = reverse_lazy('dashboard')

    def dispatch(self, request, *args, **kwargs):
        user: DepotUser = request.user

        if not (user.is_superuser or user.user_type == DepotUser.UserType.COMPANY_ADMIN):
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        # Create user from form data
        user = form.save(commit=False)
        user_type = form.cleaned_data['user_type']
        user.save()

        # Clear irrelevant permissions based on user type
        if user_type == DepotUser.UserType.CLIENT:
            user.employee_permissions.clear()
            user.company_permissions.set(form.cleaned_data['company_permissions'])
        elif user_type == DepotUser.UserType.EMPLOYEE:
            user.company_permissions.clear()
            user.employee_permissions.set(form.cleaned_data['employee_permissions'])

        return super().form_valid(form)

    def get_form(self, form_class = None):
        form = super().get_form(form_class)
        user: DepotUser = self.request.user

        if user.is_superuser:
            # Superuser can manage all permissions and user types
            form.fields['user_type'].widget.attrs['disabled'] = False
            form.fields['company_permissions'].widget.attrs['disabled'] = False
            form.fields['employee_permissions'].widget.attrs['disabled'] = False

            # Show relevant permissions based on selected user type
            if form.initial.get('user_type') == DepotUser.UserType.CLIENT:
                form.fields['employee_permissions'].widget.attrs['disabled'] = True
            elif form.initial.get('user_type') == DepotUser.UserType.EMPLOYEE:
                form.fields['company_permissions'].widget.attrs['disabled'] = True

        elif user.user_type == DepotUser.UserType.COMPANY_ADMIN:
            form.fields['company'].queryset = form.fields['company'].queryset.filter(pk=user.company.pk)
            form.fields['company'].initial = user.company
            form.fields['company'].widget.readonly = True  # form.fields['line'].widget.attrs['disabled'] = True
            form.fields['line'].queryset = form.fields['line'].queryset.filter(company=user.company.pk)

            form.fields['user_type'].choices = [
                (DepotUser.UserType.CLIENT, 'Client')
            ]
            form.fields['user_type'].initial = DepotUser.UserType.CLIENT

            form.fields['company_permissions'].widget.attrs['disabled'] = False
            form.fields['employee_permissions'].widget.attrs['disabled'] = True

        return form

class UserListView(ListView):
    template_name = 'registration/user-list.html'
    model = get_user_model()
    context_object_name = 'objects'
    paginate_by = 30  # Number of containers per page
    base_template = 'employee-base.html'

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


class UserUpdateView(UpdateView):
    template_name = 'registration/register.html'
    form_class = RegisterForm
    model = get_user_model()
    success_url = reverse_lazy('user_list')

    def dispatch(self, request, *args, **kwargs):
        user: DepotUser = request.user

        if not (user.is_superuser or user.user_type == DepotUser.UserType.COMPANY_ADMIN):
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        user = form.save(commit=False)
        user_type = form.cleaned_data['user_type']
        user.save()
        # Clear irrelevant permissions based on user type
        if user_type == DepotUser.UserType.CLIENT:
            user.employee_permissions.clear()
            user.company_permissions.set(form.cleaned_data['company_permissions'])
        elif user_type == DepotUser.UserType.EMPLOYEE:
            user.company_permissions.clear()
            user.employee_permissions.set(form.cleaned_data['employee_permissions'])
        return super().form_valid(form)

    def get_form(self, form_class = None):
        form = super().get_form(form_class)
        user: DepotUser = self.request.user

        if user.is_superuser:
            # Superuser can manage all permissions and user types
            form.fields['user_type'].widget.attrs['disabled'] = False
            form.fields['company_permissions'].widget.attrs['disabled'] = False
            form.fields['employee_permissions'].widget.attrs['disabled'] = False

            # Show relevant permissions based on selected user type
            if form.initial.get('user_type') == DepotUser.UserType.CLIENT:
                form.fields['employee_permissions'].widget.attrs['disabled'] = True
            elif form.initial.get('user_type') == DepotUser.UserType.EMPLOYEE:
                form.fields['company_permissions'].widget.attrs['disabled'] = True

        elif user.user_type == DepotUser.UserType.COMPANY_ADMIN:
            form.fields['company'].queryset = form.fields['company'].queryset.filter(pk=user.company.pk)
            form.fields['company'].initial = user.company
            form.fields['company'].widget.readonly = True
            form.fields['line'].queryset = form.fields['line'].queryset.filter(company=user.company.pk)
            form.fields['user_type'].choices = [
                (DepotUser.UserType.CLIENT, 'Client')
            ]
            form.fields['user_type'].initial = DepotUser.UserType.CLIENT
            form.fields['company_permissions'].widget.attrs['disabled'] = False
            form.fields['employee_permissions'].widget.attrs['disabled'] = True

        return form



