from django.shortcuts import redirect
from django.utils.translation import gettext_lazy as _
from django.views.generic import CreateView, DetailView
from rules.contrib.views import AutoPermissionRequiredMixin

from servala.core.models import (
    BillingEntity,
    Organization,
    OrganizationMembership,
    ServiceInstance,
)
from servala.frontend.forms.organization import OrganizationCreateForm, OrganizationForm
from servala.frontend.views.mixins import HtmxUpdateView, OrganizationViewMixin


class OrganizationCreateView(AutoPermissionRequiredMixin, CreateView):
    form_class = OrganizationCreateForm
    model = Organization
    template_name = "frontend/organizations/create.html"

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user
        return kwargs

    def form_valid(self, form):
        billing_choice = form.cleaned_data.get("billing_processing_choice")
        billing_entity = None
        name = form.cleaned_data["name"]

        if not billing_choice or billing_choice == "new":
            billing_entity = BillingEntity.create_from_data(
                name,
                {
                    key: value
                    for key, value in form.cleaned_data.items()
                    if key.startswith("invoice_")
                },
            )
        elif odoo_id := form.cleaned_data.get("existing_odoo_address_id"):
            billing_entity = BillingEntity.objects.filter(
                odoo_invoice_id=odoo_id
            ).first()

            if not billing_entity:
                billing_entity = BillingEntity.create_from_id(name, odoo_id)

        if not billing_entity:
            form.add_error(
                None,
                _(
                    "Could not determine or create the billing entity. Please check your input."
                ),
            )
            return self.form_invalid(form)

        form.instance.billing_entity = billing_entity
        instance = form.instance.create_organization(
            form.instance, owner=self.request.user
        )
        return redirect(instance.urls.base)


class OrganizationDashboardView(
    AutoPermissionRequiredMixin, OrganizationViewMixin, DetailView
):
    template_name = "frontend/organizations/dashboard.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        organization = self.get_object()

        service_instances = ServiceInstance.objects.filter(organization=organization)
        recent_instances = service_instances.order_by("-created_at")[:5]

        for instance in recent_instances:
            instance.has_change_permission = self.request.user.has_perm(
                "core.change_serviceinstance", instance
            )

        user_membership = OrganizationMembership.objects.filter(
            user=self.request.user, organization=organization
        ).first()
        user_role = user_membership.role if user_membership else None

        context.update(
            {
                "service_instances_count": service_instances.count(),
                "service_instances": recent_instances,
                "members_count": organization.members.count(),
                "has_instances": service_instances.exists(),
                "user_role": user_role,
            }
        )

        return context


class OrganizationUpdateView(OrganizationViewMixin, HtmxUpdateView):
    template_name = "frontend/organizations/update.html"
    form_class = OrganizationForm
    fragments = ("org-name", "org-name-edit")

    def get_success_url(self):
        return self.request.path
