from django import forms
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _

from servala.core.models import Organization
from servala.core.odoo import get_invoice_addresses, get_odoo_countries
from servala.frontend.forms.mixins import HtmxMixin


class OrganizationForm(HtmxMixin, ModelForm):
    class Meta:
        model = Organization
        fields = ("name",)


class OrganizationCreateForm(OrganizationForm):
    billing_processing_choice = forms.ChoiceField(
        choices=[
            ("existing", _("Use an existing billing address")),
            ("new", _("Create a new billing address")),
        ],
        widget=forms.RadioSelect,
        label=_("Billing Address"),
        initial="new",  # Will change to 'existing' if options are found
    )
    existing_odoo_address_id = forms.ChoiceField(
        label=_("Existing Billing Address"),
        required=False,
    )

    # Fields for creating a new billing address in Odoo, prefixed with 'invoice_'
    invoice_street = forms.CharField(label=_("Line 1"), required=False, max_length=100)
    invoice_street2 = forms.CharField(label=_("Line 2"), required=False, max_length=100)
    invoice_city = forms.CharField(label=_("City"), required=False, max_length=100)
    invoice_zip = forms.CharField(label=_("Postal Code"), required=False, max_length=20)
    invoice_country = forms.ChoiceField(
        label=_("Country"),
        required=False,
        choices=get_odoo_countries(),
    )
    invoice_email = forms.EmailField(label=_("Billing Email"), required=False)
    invoice_phone = forms.CharField(label=_("Phone"), required=False, max_length=30)

    class Meta(OrganizationForm.Meta):
        pass

    def __init__(self, *args, user=None, **kwargs):
        super().__init__(*args, **kwargs)

        if not self.initial.get("invoice_country"):
            default_country_name = "Switzerland"
            country_choices = self.fields["invoice_country"].choices
            for country_id, country_name_label in country_choices:
                if country_name_label == default_country_name:
                    self.initial["invoice_country"] = country_id
                    break

        self.user = user
        self.odoo_addresses = get_invoice_addresses(self.user)

        if self.odoo_addresses:
            address_choices = [("", _("---------"))]
            for addr in self.odoo_addresses:
                parent_name = None
                parent_info = addr.get("parent_id")
                if (
                    parent_info
                    and isinstance(parent_info, (list, tuple))
                    and len(parent_info) > 1
                ):
                    parent_name = parent_info[1]

                display_parts = [
                    parent_name,
                    addr.get("name"),
                    addr.get("street"),
                    addr.get("city"),
                    addr.get("zip"),
                ]
                display_name = ", ".join([part for part in display_parts if part])
                address_choices.append((str(addr["id"]), display_name))

            self.fields["existing_odoo_address_id"].choices = address_choices
            if not self.is_bound and "billing_processing_choice" not in self.initial:
                self.fields["billing_processing_choice"].initial = "existing"
        else:
            self.fields.pop("billing_processing_choice")
            self.fields["existing_odoo_address_id"].widget = forms.HiddenInput()

    def clean(self):
        cleaned_data = super().clean()
        choice = cleaned_data.get("billing_processing_choice")
        if not choice or choice == "new":
            required_fields = [
                "invoice_street",
                "invoice_city",
                "invoice_zip",
                "invoice_country",
                "invoice_email",
            ]
            for field_name in required_fields:
                if not cleaned_data.get(field_name):
                    self.add_error(field_name, _("This field is required."))
        else:
            existing_id_str = cleaned_data.get("existing_odoo_address_id")
            if not existing_id_str:
                self.add_error(
                    "existing_odoo_address_id", _("Please select an invoice address.")
                )
        return cleaned_data
