from django import forms
from django.contrib.auth import get_user_model

from .models import Ticket, TicketReply


class TicketForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            widget = field.widget
            base_class = "form-select" if isinstance(widget, forms.Select) else "form-control"
            widget.attrs["class"] = f"{widget.attrs.get('class', '')} {base_class}".strip()

    class Meta:
        model = Ticket
        fields = [
            "requester_name",
            "requester_email",
            "category",
            "priority",
            "subject",
            "description",
        ]
        widgets = {
            "requester_name": forms.TextInput(attrs={"placeholder": "Alex Morgan"}),
            "requester_email": forms.EmailInput(attrs={"placeholder": "alex@company.com"}),
            "subject": forms.TextInput(attrs={"placeholder": "Briefly describe the issue"}),
            "description": forms.Textarea(attrs={"rows": 5, "placeholder": "Share what happened, who is affected, and any useful context."}),
        }
        labels = {
            "requester_name": "Your name",
            "requester_email": "Email",
            "description": "What can we help with?",
        }


class ReplyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            widget = field.widget
            base_class = "form-select" if isinstance(widget, forms.Select) else "form-control"
            widget.attrs["class"] = f"{widget.attrs.get('class', '')} {base_class}".strip()

    class Meta:
        model = TicketReply
        fields = ["author_name", "author_email", "body"]
        widgets = {
            "author_name": forms.TextInput(attrs={"placeholder": "Your name"}),
            "author_email": forms.EmailInput(attrs={"placeholder": "you@company.com"}),
            "body": forms.Textarea(attrs={"rows": 4, "placeholder": "Write a helpful update or reply..."}),
        }
        labels = {
            "author_name": "Name",
            "author_email": "Email",
            "body": "Reply",
        }


class TicketTriageForm(forms.ModelForm):
    class Meta:
        model = Ticket
        fields = ["status", "priority", "assigned_to"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        User = get_user_model()
        self.fields["assigned_to"].queryset = User.objects.filter(is_staff=True).order_by("username")
        self.fields["assigned_to"].empty_label = "Unassigned"
        for field in self.fields.values():
            widget = field.widget
            base_class = "form-select" if isinstance(widget, forms.Select) else "form-control"
            widget.attrs["class"] = f"{widget.attrs.get('class', '')} {base_class}".strip()
