from django.contrib.auth import get_user_model
from django.core.validators import RegexValidator
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator
from datetime import date, datetime, timedelta
from verify_trusted.companies.models import Company, Subscription
from verify_trusted.users.models import Profile
from verify_trusted.widgets.models import Widget

User = get_user_model()


class UserCompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ["id", "name", "url", "currency_symbol", "is_verified"]


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["user", "first_name", "last_name", "photo", "address", "language", "due_date", "unsubscribe_email", "connect_token", "shopify_url", "charge_id", "phone_number", "active"]

    def create(self, validated_data):
        validated_data['user'] = User.objects.filter(pk=validated_data['user']).first()
        profile = Profile(**validated_data)
        profile.save()
        return profile


class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()
    is_owner = serializers.BooleanField(read_only=True, required=False, default=False)
    companies = UserCompanySerializer(required=False, many=True)
    is_expire = serializers.SerializerMethodField()
    is_trial = serializers.SerializerMethodField()
    due_date = serializers.SerializerMethodField()
    widget_id = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = [
            "id",
            "email",
            "name",
            'is_superuser',
            "profile",
            "is_owner",
            "companies",
            "ip",
            "is_expire",
            "is_trial",
            "due_date",
            "widget_id",
        ]

    def get_is_expire(self, obj):
        subscription = Subscription.objects.filter(company__user=obj.profile.user).first()
        if subscription is not None:
            return subscription.due_date <= date.today()
        return False

    def get_is_trial(self, obj):
        subscription = Subscription.objects.filter(company__user=obj.profile.user).first()
        return subscription.payment is None if subscription else False

    def get_due_date(self, obj):
        subscription = Subscription.objects.filter(company__user=obj.profile.user).first()
        return subscription.due_date if subscription else None
    
    def get_widget_id(self, obj):
        widget = Widget.objects.filter(company__user=obj.profile.user).first()
        return widget.id if widget else None


class CreateProfileSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=None)

    class Meta:
        model = Profile
        fields = '__all__'

    def create(self, validated_data):
        profile = Profile(**validated_data)
        profile.save()
        return profile


class CreateUserSerializer(serializers.ModelSerializer):
    profile = CreateProfileSerializer()

    class Meta:
        model = User
        fields = ["email", "name", "is_superuser", "profile"]
        extra_kwargs = {
            'name': {
                'allow_blank': False,
                'required': True,
                'min_length': 6,
                'max_length': 32,
                'error_messages': {
                    'blank': 'MSG001',
                    'max_length': 'MSG003',
                    'min_length': 'MSG003',
                },
            },
            'email': {
                'allow_blank': False,
                'required': True,
                'validators': [
                    UniqueValidator(queryset=User.objects.all(), message='MSG017'),
                ],
                'error_messages': {
                    'invalid': 'MSG006',
                    'blank': 'MSG005',
                },
            },
        }

    def create(self, validated_data):
        validated_data['username'] = validated_data['email']
        validated_data['is_active'] = True
        profile = validated_data.pop('profile', None)
        user = super().create(validated_data)
        profile_serializer = CreateProfileSerializer(data=profile)
        profile_serializer.is_valid(raise_exception=True)
        profile_serializer.validated_data['user'] = user
        profile_serializer.create(profile_serializer.validated_data)
        return user


class AdminUserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = [
            "id",
            "username",
            "password",
            "is_superuser",
            "email",
            "name",
            "profile",
        ]


class AdminUpdateProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        # fields = '__all__'
        exclude = ('user',)


class AdminUpdateUserSerializer(serializers.ModelSerializer):
    profile = AdminUpdateProfileSerializer()

    class Meta:
        model = User
        fields = ("email", "name", "is_superuser", "profile")

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile', None)
        user = super().update(instance, validated_data)
        profile_serializer = ProfileUpdateSerializer(data=profile)
        profile_serializer.is_valid(raise_exception=True)
        user_profile = Profile.objects.filter(user_id=user.id)
        user_profile.update(**profile_serializer.validated_data)
        if 'photo' in profile_serializer.validated_data:
            user_photo = user_profile.first()
            user_photo.photo = profile_serializer.validated_data['photo']
            user_photo.save()
            user.profile = user_photo
        return user


class ProfileUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        # fields = '__all__'
        exclude = ('user', 'active')
        phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="MSG025")
        extra_kwargs = {'phone': {'validators': [phone_regex]}}


class UserUpdateSerializer(serializers.ModelSerializer):
    profile = ProfileUpdateSerializer()
    username = serializers.HiddenField(default=None)
    is_active = serializers.HiddenField(default=True)

    class Meta:
        model = User
        fields = ("email", "username", "is_active", "name", "profile")

    def validate(self, data):
        if 'email' in data and len(data['email']) > 0:
            user = User.objects.filter(email=data['email']).first()
            if user is not None:
                raise ValidationError({'email': "MSG017"})
            data['username'] = data['email']
            data['is_active'] = True
        else:
            data.pop('username', None)
            data.pop('is_active', None)
        return super().validate(data)

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile', None)
        user = super(UserUpdateSerializer, self).update(instance, validated_data)
        profile_serializer = ProfileUpdateSerializer(data=profile)
        profile_serializer.is_valid(raise_exception=True)
        user_profile = Profile.objects.filter(user_id=user.id)
        user_profile.update(**profile_serializer.validated_data)
        if 'photo' in profile_serializer.validated_data:
            user_photo = user_profile.first()
            user_photo.photo = profile_serializer.validated_data['photo']
            user_photo.save()
            profile_serializer.validated_data.pop('photo', None)
        return user


class EmailVerificationSerializer(serializers.ModelSerializer):
    token = serializers.CharField()

    class Meta:
        model = User
        fields = ['token']


class ResendEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']


class ContactSerializer(serializers.Serializer):
    name = serializers.CharField(
        max_length=100,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    email = serializers.EmailField(
        max_length=100,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    message = serializers.CharField(
        max_length=500,
        required=False,
        allow_blank=True,
    )
    website = serializers.CharField(
        required=False,
        allow_blank=True,
    )

    class Meta:
        fields = '__all__'


class AddShopifyUrlSerializer(serializers.Serializer):
    connect_token = serializers.CharField(
        max_length=100,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    shopify_url = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    shopify_token = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    
    class Meta:
        fields = '__all__'

class LogoutShopifyUrlSerializer(serializers.Serializer):
    connect_token = serializers.CharField(
        max_length=100,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    shopify_url = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    
    class Meta:
        fields = '__all__'

class GetUserByShopifySerializer(serializers.Serializer):
    shopify_url = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    
    class Meta:
        fields = '__all__'


class PurchasePlanSerializer(serializers.Serializer):
    plan_id = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    company_id = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    charge_id = serializers.CharField(
        max_length=250,
        required=True,
        allow_blank=False,
        error_messages={
            'blank': 'MSG005',
        },
    )
    
    class Meta:
        fields = '__all__'