from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm

from billing.models import Payment
from clients.models import Client
from services.models import Service
from support.models import SupportMessage, SupportTicket


class PortalAuthenticationForm(AuthenticationForm):
    username = forms.CharField(label="Utilizador ou email")
    password = forms.CharField(label="Palavra-passe", strip=False, widget=forms.PasswordInput)

    def confirm_login_allowed(self, user):
        super().confirm_login_allowed(user)
        # A página de entrada é unificada: administradores e colaboradores
        # podem autenticar-se aqui e são encaminhados para o backoffice.
        if user.is_staff or user.is_superuser:
            return
        try:
            access = user.client_portal_access
        except Exception as exc:
            raise forms.ValidationError(
                "Esta conta não está associada a um cliente nem possui acesso ao backoffice.",
                code="no_portal",
            ) from exc
        if not access.is_active or not access.client.portal_access_enabled:
            raise forms.ValidationError("O acesso ao portal encontra-se desativado.", code="inactive_portal")


class TicketCreateForm(forms.ModelForm):
    service = forms.ModelChoiceField(label="Serviço relacionado", queryset=Service.objects.none(), required=False)
    attachment = forms.FileField(label="Anexo", required=False)

    class Meta:
        model = SupportTicket
        fields = ("service", "subject", "category", "priority", "description")
        widgets = {
            "description": forms.Textarea(attrs={"rows": 6, "placeholder": "Descreva o pedido com o máximo de detalhe possível."}),
        }

    def __init__(self, *args, client=None, **kwargs):
        super().__init__(*args, **kwargs)
        if client:
            self.fields["service"].queryset = client.services.exclude(status="archived").order_by("name")
        self.fields["priority"].choices = [
            (SupportTicket.Priority.LOW, "Baixa"),
            (SupportTicket.Priority.NORMAL, "Normal"),
            (SupportTicket.Priority.HIGH, "Alta"),
            (SupportTicket.Priority.URGENT, "Urgente"),
        ]


class TicketReplyForm(forms.ModelForm):
    class Meta:
        model = SupportMessage
        fields = ("message", "attachment")
        widgets = {
            "message": forms.Textarea(attrs={"rows": 5, "placeholder": "Escreva a sua resposta..."}),
        }


class PaymentProofForm(forms.ModelForm):
    class Meta:
        model = Payment
        fields = ("proof",)
        widgets = {"proof": forms.ClearableFileInput(attrs={"accept": ".pdf,.png,.jpg,.jpeg"})}

    def clean_proof(self):
        value = self.cleaned_data.get("proof")
        if not value:
            raise forms.ValidationError("Selecione um comprovativo.")
        if value.size > 8 * 1024 * 1024:
            raise forms.ValidationError("O ficheiro não pode ultrapassar 8 MB.")
        return value


class ClientProfileForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ("email", "alternative_email", "phone", "address")
        widgets = {"address": forms.Textarea(attrs={"rows": 3})}


class PortalPasswordChangeForm(PasswordChangeForm):
    old_password = forms.CharField(label="Palavra-passe atual", strip=False, widget=forms.PasswordInput)
    new_password1 = forms.CharField(label="Nova palavra-passe", strip=False, widget=forms.PasswordInput)
    new_password2 = forms.CharField(label="Confirmar nova palavra-passe", strip=False, widget=forms.PasswordInput)
