from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser, FriendCode
from allauth.account.forms import SignupForm
from crispy_tailwind.tailwind import CSSContainer
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Submit

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ['email']

class FriendCodeForm(forms.ModelForm):
    class Meta:
        model = FriendCode
        fields = ["friend_code", "in_game_name"]

    def clean_friend_code(self):
        friend_code = self.cleaned_data.get("friend_code", "").strip()
        # Remove any dashes from the input for validation.
        friend_code_clean = friend_code.replace("-", "")
        if len(friend_code_clean) != 16 or not friend_code_clean.isdigit():
            raise forms.ValidationError("Friend code must be exactly 16 digits long.")
        # Format the friend code as: XXXX-XXXX-XXXX-XXXX.
        friend_code_formatted = f"{friend_code_clean[:4]}-{friend_code_clean[4:8]}-{friend_code_clean[8:12]}-{friend_code_clean[12:16]}"
        return friend_code_formatted

class CustomUserCreationForm(SignupForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ['email', 'username', 'friend_code']

    email = forms.EmailField(
        required=True,
        label="Email",
        widget=forms.TextInput(attrs={'placeholder': 'Email', 'class':'dark:bg-base-100'})
    )

    username = forms.CharField(
        max_length=24,
        required=True,
        label="Username",
        widget=forms.TextInput(attrs={'placeholder': 'Username', 'class':'dark:bg-base-100'})
    )

    friend_code = forms.CharField(
        max_length=19,
        required=True,
        label="Friend Code",
        help_text="Enter your friend code in the format XXXX-XXXX-XXXX-XXXX.",
        widget=forms.TextInput(attrs={'placeholder': 'XXXX-XXXX-XXXX-XXXX', 'class':'dark:bg-base-100'})
    )
    in_game_name = forms.CharField(
        max_length=16,
        required=True,
        label="In-Game Name",
        help_text="Enter your in-game name.",
        widget=forms.TextInput(attrs={'placeholder': 'In-Game Name', 'class':'dark:bg-base-100'})
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def clean_friend_code(self):
        friend_code = self.cleaned_data.get("friend_code", "").strip().replace("-", "")
        if len(friend_code) != 16 or not friend_code.isdigit():
            raise forms.ValidationError("Friend code must be exactly 16 digits long.")
        formatted = f"{friend_code[:4]}-{friend_code[4:8]}-{friend_code[8:12]}-{friend_code[12:16]}"
        return formatted

    def save(self, request):
        # First, complete the normal signup process.
        user = super(CustomUserCreationForm, self).save(request)
        # Create the associated FriendCode record, now including in_game_name.
        friend_code_instance = FriendCode.objects.create(
            friend_code=self.cleaned_data["friend_code"],
            in_game_name=self.cleaned_data["in_game_name"],
            user=user
        )
        user.default_friend_code = friend_code_instance
        user.save()
        return user

class UserSettingsForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['show_friend_code_on_link_previews']