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

from api.models import Profile, Opportunity, IntroductionRequest
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field


class CheckboxBeforeLabel(Field):
    template = "crispy/checkbox_before_label.html"


class ProfileCreateForm(forms.Form):
    username = forms.CharField(label="Username")
    bio = forms.CharField(label="Bio", widget=forms.Textarea, required=False)
    interests = forms.CharField(label="Interests", required=False)
    industry = forms.CharField(label="Industry", required=False)
    is_verified = forms.BooleanField(label="Verified", required=False)
    tags = forms.CharField(label="Tags", required=False, help_text="Comma-separated")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Field("username"),
            Field("bio"),
            Field("interests"),
            Field("industry"),
            Field("tags"),
            CheckboxBeforeLabel("is_verified"),
        )

    def clean_username(self):
        username = self.cleaned_data["username"].strip()
        user = User.objects.filter(username=username).first()
        if not user:
            raise forms.ValidationError("User not found.")
        if Profile.objects.filter(user=user).exists():
            raise forms.ValidationError("Profile for this user already exists.")
        return username

    def save(self):
        username = self.cleaned_data["username"].strip()
        user = User.objects.get(username=username)
        profile = Profile.objects.create(
            user=user,
            bio=self.cleaned_data.get("bio", ""),
            interests=self.cleaned_data.get("interests", ""),
            industry=self.cleaned_data.get("industry", ""),
            is_verified=self.cleaned_data.get("is_verified", False),
        )
        tags = [t.strip() for t in self.cleaned_data.get("tags", "").split(",") if t.strip()]
        try:
            if tags:
                profile.tags.set(tags)
        except Exception:
            pass
        return profile


class ProfileEditForm(forms.ModelForm):
    tags = forms.CharField(label="Tags", required=False, help_text="Comma-separated")

    class Meta:
        model = Profile
        fields = ["bio", "interests", "industry", "is_verified"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Field("bio"),
            Field("interests"),
            Field("industry"),
            Field("tags"),
            CheckboxBeforeLabel("is_verified"),
        )
        if self.instance and getattr(self.instance, "pk", None):
            try:
                names = list(self.instance.tags.names())
                self.fields["tags"].initial = ", ".join(names)
            except Exception:
                self.fields["tags"].initial = ""

    def save(self, commit=True):
        profile = super().save(commit)
        tags = [t.strip() for t in self.cleaned_data.get("tags", "").split(",") if t.strip()]
        try:
            if commit and hasattr(profile, "tags"):
                profile.tags.set(tags)
        except Exception:
            pass
        return profile


class OpportunityForm(forms.ModelForm):
    class Meta:
        model = Opportunity
        fields = ["title", "description"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Field("title"),
            Field("description"),
        )


class IntroRequestForm(forms.Form):
    from_username = forms.CharField(label="From Username")
    to_username = forms.CharField(label="To Username")
    message = forms.CharField(label="Message", widget=forms.Textarea)
    is_accepted = forms.BooleanField(label="Accepted", required=False)

    def __init__(self, *args, **kwargs):
        instance = kwargs.pop("instance", None)
        super().__init__(*args, **kwargs)
        self.instance = instance
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Field("from_username"),
            Field("to_username"),
            Field("message"),
            CheckboxBeforeLabel("is_accepted"),
        )
        if instance:
            self.fields["from_username"].initial = instance.from_user.username
            self.fields["to_username"].initial = instance.to_user.username
            self.fields["message"].initial = instance.message
            self.fields["is_accepted"].initial = instance.is_accepted

    def clean(self):
        cleaned = super().clean()
        from_username = cleaned.get("from_username", "").strip()
        to_username = cleaned.get("to_username", "").strip()
        if not from_username or not to_username:
            return cleaned
        from_user = User.objects.filter(username=from_username).first()
        to_user = User.objects.filter(username=to_username).first()
        if not from_user or not to_user:
            raise forms.ValidationError("Both users must exist.")
        if from_user == to_user:
            raise forms.ValidationError("From and To users must be different.")
        cleaned["from_user_obj"] = from_user
        cleaned["to_user_obj"] = to_user
        return cleaned

    def save(self, instance: IntroductionRequest | None = None):
        data = self.cleaned_data
        if instance is None:
            instance = IntroductionRequest()
        instance.from_user = data["from_user_obj"]
        instance.to_user = data["to_user_obj"]
        instance.message = data.get("message", "")
        instance.is_accepted = data.get("is_accepted", False)
        instance.save()
        return instance


# Recycle Core forms moved to recycle_core/forms.py
