from django import forms
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image
import io
import random
from .models import UsuarioUtrau, ColaMensajes

class LoginManualForm(forms.Form):
    username = forms.CharField(
        max_length=150, label="Usuario / Alias",
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Escribí tu Alias'})
    )
    password = forms.CharField(
        label="PIN de Acceso",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Tu PIN de 4 dígitos o más'})
    )

class RegistroManualForm(forms.ModelForm):
    class Meta:
        model = UsuarioUtrau
        fields = ['username', 'nombre_completo', 'celular', 'asistente_preferido', 'foto_perfil']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Elegí un Alias (Ej: JuanC)'}),
            'nombre_completo': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tu nombre y apellido'}),
            'celular': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ej: 099123456'}),
            'asistente_preferido': forms.RadioSelect(choices=[(1, 'El Compa (Asistente Masculino)'), (2, 'La Compa (Asistente Femenina)')]),
            'foto_perfil': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'})
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['foto_perfil'].required = True

    def clean_foto_perfil(self):
        foto = self.cleaned_data.get('foto_perfil')
        if foto and hasattr(foto, 'file'):
            try:
                img = Image.open(foto)
                if img.mode != 'RGB': img = img.convert('RGB')
                img.thumbnail((400, 400), Image.Resampling.LANCZOS)
                output = io.BytesIO()
                img.save(output, format='WEBP', quality=85)
                output.seek(0)
                nombre_limpio = foto.name.split('.')[0]
                return InMemoryUploadedFile(output, 'ImageField', f"{nombre_limpio}.webp", 'image/webp', output.getbuffer().nbytes, None)
            except Exception as e:
                print(f"Error optimizando imagen manual: {e}")
        return foto

    def save(self, commit=True):
        user = super().save(commit=False)
        
        # --- VALIDACIÓN ELIMINADA: PIN FIJO PARA PRUEBAS ---
        pin_temporal = '1234' 
        user.set_password(pin_temporal)
        user.requiere_cambio_pin = False # Lo dejamos listo para usar
        
        if commit:
            user.save()
            # ColaMensajes.objects.create(...) # Desactivamos el envío de WhatsApp
        return user


class PerfilUsuarioForm(forms.ModelForm):
    class Meta:
        model = UsuarioUtrau
        fields = ['username', 'nombre_completo', 'asistente_preferido', 'foto_perfil']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control'}),
            'nombre_completo': forms.TextInput(attrs={'class': 'form-control'}),
            'asistente_preferido': forms.RadioSelect(choices=[(1, 'El Compa (Asistente Masculino)'), (2, 'La Compa (Asistente Femenina)')]),
            'foto_perfil': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'})
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        user = self.instance
        
        # EL BLINDAJE DE IDENTIDAD SOCIAL
        if user and (getattr(user, 'id_google', None) or getattr(user, 'id_facebook', None)):
            self.fields['username'].disabled = True
            self.fields['username'].help_text = "Tu alias fue generado por tu red social y no se puede modificar por seguridad."

    def clean_foto_perfil(self):
        foto = self.cleaned_data.get('foto_perfil')
        if foto and hasattr(foto, 'file'):
            try:
                img = Image.open(foto)
                if img.mode != 'RGB': img = img.convert('RGB')
                img.thumbnail((400, 400), Image.Resampling.LANCZOS)
                output = io.BytesIO()
                img.save(output, format='WEBP', quality=85)
                output.seek(0)
                nombre_limpio = foto.name.split('.')[0] if '.' in foto.name else 'perfil'
                return InMemoryUploadedFile(output, 'ImageField', f"{nombre_limpio}.webp", 'image/webp', output.getbuffer().nbytes, None)
            except Exception: pass
        return foto