from django.contrib import messages
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView

from servala.core.odoo import create_helpdesk_ticket
from servala.frontend.forms.support import SupportForm
from servala.frontend.views.mixins import OrganizationViewMixin


class SupportView(OrganizationViewMixin, FormView):
    form_class = SupportForm
    template_name = "frontend/organizations/support.html"

    def form_valid(self, form):
        message = form.cleaned_data["message"]
        organization = self.organization
        user = self.request.user

        try:
            partner_id = user.get_or_create_odoo_contact(organization)
            if not partner_id:
                raise Exception("Could not get or create Odoo contact for user")

            # All orgs should have a sale order ID, but legacy ones might not have it.
            # Also, we want to be very sure that support requests work, especially for
            # organizations where something in the creation process may have gone wrong,
            # so if the ID does not exist, we omit it entirely.
            create_helpdesk_ticket(
                title=f"Servala Support - Organization {organization.name}",
                description=message,
                partner_id=partner_id,
                sale_order_id=organization.odoo_sale_order_id or None,
            )
            messages.success(
                self.request,
                _(
                    "Your support request has been submitted successfully. We will contact you shortly."
                ),
            )

        except Exception as e:
            messages.error(
                self.request,
                mark_safe(
                    _(
                        "There was an error submitting your support request. "
                        'Please try again or contact us directly at <a href="mailto:servala-support@vshn.ch">servala-support@vshn.ch</a>.'
                    )
                ),
            )
            print(f"Error creating helpdesk ticket: {e}")

        return redirect(self.request.path)
