from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import (
    Inbox, AnonymousMessage,
    Conversation, DirectMessage, ConversationReadState,
)

User = get_user_model()


# ---------------------------------------------------------------------------
# Inbox / Anonymous Message serializers
# ---------------------------------------------------------------------------

class PublicInboxSerializer(serializers.ModelSerializer):
    owner_display_name = serializers.CharField(source='owner.profile.display_name', read_only=True)
    owner_bio = serializers.CharField(source='owner.profile.bio', read_only=True)
    owner_username = serializers.CharField(source='owner.username', read_only=True)
    owner_avatar_url = serializers.SerializerMethodField()
    owner_cover_url = serializers.SerializerMethodField()

    class Meta:
        model = Inbox
        fields = [
            'slug', 'anonymous_enabled',
            'owner_display_name', 'owner_bio', 'owner_username',
            'owner_avatar_url', 'owner_cover_url',
        ]

    def get_owner_avatar_url(self, obj):
        if hasattr(obj.owner, 'profile') and obj.owner.profile.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.owner.profile.avatar.url)
            return obj.owner.profile.avatar.url
        return None

    def get_owner_cover_url(self, obj):
        if hasattr(obj.owner, 'profile') and obj.owner.profile.cover:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.owner.profile.cover.url)
            return obj.owner.profile.cover.url
        return None


class AnonymousMessageSubmitSerializer(serializers.Serializer):
    body = serializers.CharField(min_length=1, max_length=500)
    website = serializers.CharField(required=False, allow_blank=True, default='')

    def validate_body(self, value):
        text = (value or '').strip()
        if not text:
            raise serializers.ValidationError("Message body cannot be empty.")
        if len(text) > 500:
            raise serializers.ValidationError("Message body cannot exceed 500 characters.")
        return text


class OwnerMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnonymousMessage
        fields = ['id', 'body', 'is_read', 'created_at']
        read_only_fields = ['id', 'body', 'created_at']


class InboxSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Inbox
        fields = ['slug', 'anonymous_enabled', 'created_at']
        read_only_fields = ['slug', 'created_at']


# ---------------------------------------------------------------------------
# Direct Messaging serializers
# ---------------------------------------------------------------------------

class DirectMessageSerializer(serializers.ModelSerializer):
    sender_username = serializers.CharField(source='sender.username', read_only=True)

    class Meta:
        model = DirectMessage
        fields = ['id', 'conversation_id', 'sender_id', 'sender_username', 'body', 'created_at']
        read_only_fields = ['id', 'conversation_id', 'sender_id', 'sender_username', 'created_at']


class SendDirectMessageSerializer(serializers.Serializer):
    body = serializers.CharField(min_length=1, max_length=1000)

    def validate_body(self, value):
        text = (value or '').strip()
        if not text:
            raise serializers.ValidationError("Message body cannot be empty.")
        if len(text) > 1000:
            raise serializers.ValidationError("Message body cannot exceed 1000 characters.")
        return text


class ConversationDetailSerializer(serializers.ModelSerializer):
    other_user = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()
    unread = serializers.SerializerMethodField()

    class Meta:
        model = Conversation
        fields = ['id', 'created_at', 'other_user', 'last_message', 'unread']

    def get_other_user(self, obj):
        request = self.context.get('request')
        if not request:
            return None
        other = obj.get_other_user(request.user)
        if not other:
            return None
        return {
            'id': other.id,
            'username': other.username,
            'display_name': (
                getattr(other.profile, 'display_name', other.username)
                if hasattr(other, 'profile') else other.username
            ),
            'is_suspended': other.is_suspended,
        }

    def get_last_message(self, obj):
        request = self.context.get('request')
        user = request.user if request else None
        for m in obj.messages.all().order_by('-id'):
            if user and m.is_visible_to(user):
                return DirectMessageSerializer(m).data
        return None

    def get_unread(self, obj):
        request = self.context.get('request')
        if not request:
            return False
        user = request.user
        read_state = ConversationReadState.objects.filter(conversation=obj, user=user).first()
        last_read_id = read_state.last_read_message_id if read_state else 0
        last_msg = obj.messages.exclude(sender=user).order_by('-id').first()
        if not last_msg:
            return False
        return last_msg.id > (last_read_id or 0)
