from django import forms
from .models import EntertainmentBrand
from django.contrib.auth import get_user_model
from .models import CreatorMedia, MediaLike, Message

class BootstrapFormMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            widget = field.widget
            existing_classes = widget.attrs.get("class", "").split()
            if isinstance(widget, (forms.CheckboxInput, forms.CheckboxSelectMultiple, forms.RadioSelect)):
                if "form-check-input" not in existing_classes:
                    existing_classes.append("form-check-input")
            else:
                if "form-control" not in existing_classes:
                    existing_classes.append("form-control")
            widget.attrs["class"] = " ".join(existing_classes).strip()

PAYMENT_PROVIDER_CHOICES = [
    ("stripe", "Stripe"),
    ("paystack", "Paystack"),
    ("flutterwave", "Flutterwave"),
    ("btc", "Bitcoin (BTC)"),
    ("usdt", "USDT (TRC20)"),
]

class EntertainmentBrandForm(BootstrapFormMixin, forms.ModelForm):
    class Meta:
        model = EntertainmentBrand
        fields = [
            "name",
            "logo",
            "website",
            "description",
            "category",
            "status",
            "is_verified",
            "is_featured",
            "trust_score",
            "contact_email",
            "contact_phone",
            "instagram",
            "twitter",
            "youtube",
            "linkedin",
            "notes",
            "display_order",
            "is_active",
        ]
        widgets = {
            "description": forms.Textarea(attrs={"rows": 4}),
            "notes": forms.Textarea(attrs={"rows": 3}),
            "trust_score": forms.NumberInput(attrs={"min": 0, "max": 100}),
        }

    def clean_trust_score(self):
        score = self.cleaned_data.get("trust_score")
        if score is not None and (score < 0 or score > 100):
            raise forms.ValidationError("Trust score must be between 0 and 100.")
        return score
    
    
class ProfileSearchForm(BootstrapFormMixin, forms.Form):
    keyword = forms.CharField(required=False, label="Keyword")
    city = forms.CharField(required=False, label="City")
    country = forms.CharField(required=False, label="Country")
    interest = forms.CharField(required=False, label="Interest")
    category = forms.ChoiceField(
        required=False,
        choices=[("", "All media categories")] + list(CreatorMedia.Category.choices),
        label="Category",
    )
    verified_only = forms.BooleanField(required=False, label="Only verified accounts")


class PaymentSelectionForm(BootstrapFormMixin, forms.Form):
    provider = forms.ChoiceField(
        choices=PAYMENT_PROVIDER_CHOICES,
        widget=forms.RadioSelect(attrs={"class": "form-check-input"}),
        initial="stripe",
        label="Choose a payment provider",
    )


class NewMessageThreadForm(BootstrapFormMixin, forms.Form):
    recipient = forms.CharField(max_length=150, label="Recipient username")
    title = forms.CharField(max_length=220, required=False, label="Thread title")
    body = forms.CharField(widget=forms.Textarea(attrs={"rows": 4}), label="Message")

    def clean_recipient(self):
        username = self.cleaned_data["recipient"].strip()
        User = get_user_model()
        try:
            user = User.objects.get(username__iexact=username)
            return user.username  # Return username string, not User object
        except User.DoesNotExist:
            raise forms.ValidationError("Recipient not found.")


class MessageReplyForm(BootstrapFormMixin, forms.ModelForm):
    class Meta:
        model = Message
        fields = ["body"]
        widgets = {
            "body": forms.Textarea(attrs={"rows": 4}),
        }


class CreatorMediaForm(BootstrapFormMixin, forms.ModelForm):
    class Meta:
        model = CreatorMedia
        fields = ["title", "description", "category", "media_type", "media_file"]
        widgets = {
            "description": forms.Textarea(attrs={"rows": 4}),
        }


class BookingRequestForm(BootstrapFormMixin, forms.Form):
    preferred_date = forms.DateField(required=False, widget=forms.DateInput(attrs={"type": "date"}))
    message = forms.CharField(widget=forms.Textarea(attrs={"rows": 4}), required=False)


class WalletDepositForm(BootstrapFormMixin, forms.Form):
    provider = forms.ChoiceField(
        choices=[
            ("usdt", "USDT"),
            ("btc", "BTC"),
            ("bank", "Bank Transfer"),
        ],
        label="Deposit method",
    )
    amount = forms.DecimalField(min_value=1, max_digits=12, decimal_places=2, label="Amount (USD)")


class WithdrawalRequestForm(BootstrapFormMixin, forms.Form):
    provider = forms.ChoiceField(
        choices=[
            ("bank", "Bank Transfer"),
            ("usdt", "USDT"),
            ("btc", "BTC"),
        ],
        label="Withdrawal method",
    )
    amount = forms.DecimalField(min_value=10, max_digits=12, decimal_places=2, label="Amount (USD)")
