"""Forms for PI FYAD plugin."""

from django import forms

from .constants import PLANET_TYPES, VISIBILITY_CHOICES
from .models import PlanetTemplate


class PlanetTemplateForm(forms.ModelForm):
    """Form for creating a PI planet template from clipboard."""

    clipboard_raw = forms.CharField(
        widget=forms.Textarea(attrs={
            "rows": 12,
            "placeholder": "Paste your PI clipboard export here...",
            "class": "form-control",
        }),
        help_text="Paste the clipboard text from EVE's PI export.",
    )

    planet_type_id = forms.ChoiceField(
        choices=[(k, v) for k, v in PLANET_TYPES.items()],
        widget=forms.Select(attrs={"class": "form-select"}),
        help_text="Select the planet type this template is designed for.",
    )

    visibility = forms.ChoiceField(
        choices=VISIBILITY_CHOICES,
        widget=forms.Select(attrs={"class": "form-select"}),
        initial="private",
    )

    class Meta:
        model = PlanetTemplate
        fields = ["name", "description", "planet_type_id", "visibility", "clipboard_raw"]
        widgets = {
            "name": forms.TextInput(attrs={
                "class": "form-control",
                "placeholder": "Template name",
            }),
            "description": forms.Textarea(attrs={
                "class": "form-control",
                "rows": 3,
                "placeholder": "Optional description...",
            }),
        }

    def clean_planet_type_id(self):
        """Validate and convert planet type ID."""
        value = self.cleaned_data["planet_type_id"]
        try:
            type_id = int(value)
        except (ValueError, TypeError):
            raise forms.ValidationError("Invalid planet type.")
        if type_id not in PLANET_TYPES:
            raise forms.ValidationError("Unknown planet type.")
        return type_id

    def save(self, commit=True):
        """Save with planet type name populated."""
        instance = super().save(commit=False)
        instance.planet_type_name = PLANET_TYPES.get(
            instance.planet_type_id, "Unknown"
        )
        if commit:
            instance.save()
        return instance
