from rest_framework import serializers, status
from django.contrib.auth import authenticate
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from profiles.models import Account
from django.db import IntegrityError


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email']


class RegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        error_messages={
            "required": "Username harus diisi",
            "invalid": "Username yang diisi tidak sesuai dengan format",
            "unique": "Username sudah terdaftar. Silakan gunakan username lain",
        },
    )
    email = serializers.CharField(
        error_messages={
            "required": "Email harus diisi",
            "invalid": "Email yang diisi tidak sesuai dengan format",
            "unique": "Email sudah terdaftar. Silakan gunakan email lain.",
        },
    )
    phone = serializers.CharField(max_length=20, required=False, error_messages={
        "unique": "Nomor telepon sudah terdaftar. Silakan gunakan nomor lain.",
    },)

    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['first_name', 'last_name',
                  'username', 'email', 'phone', 'password']

    def create(self, validated_data):
        phone = validated_data.pop('phone', None)
        first_name = validated_data.get('first_name', '')
        words = first_name.split()

        if len(words) > 1 and 'last_name' not in validated_data:
            first_name = words[0]
            last_name = ' '.join(words[1:])
            validated_data['first_name'] = first_name
            validated_data['last_name'] = last_name

        try:
            user = User.objects.create_user(**validated_data)
            Account.objects.create(user=user, phone=phone)
        except IntegrityError:
            error_message = "Username atau email sudah pernah digunakan"
            raise serializers.ValidationError(
                {"message": error_message}, code=status.HTTP_400_BAD_REQUEST)

        return user


class AuthTokenSerializer(serializers.Serializer):
    username = serializers.CharField(
        label=_("Username"),
        error_messages={'required': 'Username harus diisi'}
    )
    password = serializers.CharField(
        label=_("Password"),
        style={'input_type': 'password'},
        trim_whitespace=False,
        write_only=True,
        error_messages={'required': 'Password harus diisi'}
    )
    token = serializers.CharField(
        label=_("Token"),
        read_only=True
    )

    extra_kwargs = {
        "username": {
            "error_messages": {
                "required": "Username harus diisi",
                "invalid": "Username yang diisi tidak sesuai dengan format"
            }
        }
    }

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username, password=password)

            if not user:
                msg = _('Username atau password salah')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('Harap masukan "username" dan "password"')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
