from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

from .models import Activity, Asset, Species


def _bootstrapify(form):
    for field in form.fields.values():
        widget = field.widget
        if isinstance(widget, (forms.CheckboxInput, forms.CheckboxSelectMultiple)):
            continue
        css = "form-select" if isinstance(widget, forms.Select) else "form-control"
        widget.attrs.setdefault("class", css)


class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ["username", "password1", "password2"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        _bootstrapify(self)


class OnboardingAccountForm(forms.Form):
    name = forms.CharField(max_length=150, label="Name")
    phone = forms.CharField(max_length=30, label="Phone Number")
    county = forms.CharField(max_length=100, label="County")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        _bootstrapify(self)

    def clean_phone(self):
        phone = self.cleaned_data["phone"].strip()
        username = "u" + "".join(ch for ch in phone if ch.isdigit())
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("An account with this phone number already exists.")
        return phone


class TreeAssetForm(forms.ModelForm):
    """Register a tree: camera -> species -> (silent GPS) -> optional name/owner.
    Latitude/longitude are captured automatically and never shown as numbers."""

    class Meta:
        model = Asset
        fields = ["species", "name", "latitude", "longitude", "source_nursery", "planted_date"]
        widgets = {
            "planted_date": forms.DateInput(attrs={"type": "date"}),
            "latitude": forms.HiddenInput(),
            "longitude": forms.HiddenInput(),
            "name": forms.TextInput(attrs={"placeholder": "e.g. Gate Tree, Peter's Mango"}),
        }
        labels = {"name": "Tree Name (optional)"}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["source_nursery"].queryset = Asset.objects.filter(asset_type="nursery")
        self.fields["source_nursery"].label = "Nursery"
        for f in ("name", "source_nursery", "planted_date"):
            self.fields[f].required = False
        _bootstrapify(self)


class NurseryAssetForm(forms.ModelForm):
    """Register a nursery asset (wizard flow): name + species + capacity."""

    class Meta:
        model = Asset
        fields = ["name", "seedling_capacity", "species_available", "latitude", "longitude"]
        widgets = {
            "latitude": forms.HiddenInput(),
            "longitude": forms.HiddenInput(),
            "species_available": forms.SelectMultiple(attrs={"size": 4}),
            "name": forms.TextInput(attrs={"placeholder": "e.g. Wundanyi Nursery"}),
        }
        labels = {"seedling_capacity": "Seedling Capacity", "name": "Nursery Name"}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["species_available"].required = False
        _bootstrapify(self)


class PlantingSessionForm(forms.Form):
    species = forms.ModelChoiceField(queryset=Species.objects.all())
    quantity = forms.IntegerField(min_value=1, max_value=1000, initial=50)
    county = forms.CharField(required=False)
    planted_date = forms.DateField(required=False, widget=forms.DateInput(attrs={"type": "date"}))
    latitude = forms.FloatField(widget=forms.HiddenInput())
    longitude = forms.FloatField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        _bootstrapify(self)


class ActivityForm(forms.ModelForm):
    class Meta:
        model = Activity
        fields = ["activity_type", "note", "height_cm"]
        widgets = {"note": forms.TextInput(attrs={"placeholder": "Optional note"})}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["activity_type"].choices = [
            ("watered", "💧 Watered"),
            ("observed", "👀 Observed"),
            ("transplanted", "🪴 Transplanted"),
            ("pruned", "✂️ Pruned"),
            ("photo", "📷 Photo"),
        ]
        self.fields["note"].required = False
        self.fields["height_cm"].required = False
        _bootstrapify(self)
