"""Hull section forms: stockroom price rule + per-hull stock/price modes."""

from django import forms
from eveuniverse.models import EveType

from ...forms import AddStockroomForm
from ...models import (
    FIXED_PRICE,
    FIXED_STOCK,
    PCT_MODES,
    PRICE_MODE_CHOICES,
    STOCK_MODE_CHOICES,
)
from .stock import SHIP_CATEGORY_ID


def ship_type_queryset():
    return EveType.objects.filter(
        eve_group__eve_category_id=SHIP_CATEGORY_ID, published=True
    ).order_by("name")


class HullStockroomForm(AddStockroomForm):
    """Hull stockroom adds a default price rule inherited by first-seen hulls."""

    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price_pct = forms.DecimalField(
        min_value=0, max_digits=5, decimal_places=2, required=False
    )

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned


class EditStockroomForm(forms.Form):
    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price_pct = forms.DecimalField(
        min_value=0, max_digits=5, decimal_places=2, required=False
    )

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned


class HullModeFieldsMixin(forms.Form):
    stock_mode = forms.ChoiceField(choices=STOCK_MODE_CHOICES)
    stock = forms.IntegerField(min_value=0, required=False)
    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price = forms.IntegerField(min_value=0, required=False)  # ISK, fixed mode
    price_pct = forms.DecimalField(
        min_value=0, max_digits=5, decimal_places=2, required=False
    )
    persist = forms.BooleanField(required=False)  # keep listing at 0 stock
    description = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4}),
        help_text="Markdown supported.",
    )

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("stock_mode") == FIXED_STOCK and cleaned.get("stock") is None:
            self.add_error("stock", "Enter a stock quantity for fixed stock.")
        if cleaned.get("price_mode") == FIXED_PRICE and cleaned.get("price") is None:
            self.add_error("price", "Enter a price (0 = Ask) for fixed price.")
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned


class EditHullForm(HullModeFieldsMixin):
    pass


class AddHullForm(HullModeFieldsMixin):
    eve_type = forms.ModelChoiceField(queryset=EveType.objects.none(), label="Ship")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["eve_type"].queryset = ship_type_queryset()
        self.fields["eve_type"].widget.attrs["class"] = "form-select"
