from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Task, TaskComment, TaskAttachment

User = get_user_model()

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


class TaskAttachmentSerializer(serializers.ModelSerializer):
    file_url = serializers.SerializerMethodField()
    file_name = serializers.SerializerMethodField()
    file_size = serializers.SerializerMethodField()
    uploaded_by = UserSerializer(read_only=True)

    class Meta:
        model = TaskAttachment
        fields = [
            'id', 'file', 'file_url', 'file_name', 'file_size',
            'description', 'uploaded_by', 'uploaded_at'
        ]
        read_only_fields = ['id', 'uploaded_by', 'uploaded_at']
    
    def get_file_url(self, obj):
        if obj.file:
            return obj.file.url
        return None
    
    def get_file_name(self, obj):
        if obj.file:
            return obj.file.name.split('/')[-1]
        return None
    
    def get_file_size(self, obj):
        if obj.file:
            size = obj.file.size
            if size < 1024:
                return f"{size} B"
            elif size < 1024 * 1024:
                return f"{size / 1024:.1f} KB"
            else:
                return f"{size / (1024 * 1024):.1f} MB"
        return None


class TaskCommentSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    can_edit = serializers.SerializerMethodField()
    can_delete = serializers.SerializerMethodField()

    class Meta:
        model = TaskComment
        fields = [
            'id', 'content', 'author', 'created_at', 'updated_at',
            'can_edit', 'can_delete'
        ]
        read_only_fields = ['id', 'author', 'created_at', 'updated_at']
    
    def get_can_edit(self, obj):
        request = self.context.get('request')
        if request:
            return obj.author == request.user or request.user.is_staff
        return False
    
    def get_can_delete(self, obj):
        return self.get_can_edit(obj)


class TaskSerializer(serializers.ModelSerializer):
    created_by = UserSerializer(read_only=True)
    assigned_to = UserSerializer(read_only=True)
    assignee_name = serializers.SerializerMethodField()
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    priority_display = serializers.CharField(source='get_priority_display', read_only=True)
    is_overdue = serializers.BooleanField(read_only=True)
    comments = TaskCommentSerializer(many=True, read_only=True)
    attachments = TaskAttachmentSerializer(many=True, read_only=True)
    can_edit = serializers.SerializerMethodField()
    can_delete = serializers.SerializerMethodField()
    can_complete = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = [
            'id', 'title', 'description', 'due_date', 'priority', 'priority_display',
            'status', 'status_display', 'created_by', 'assigned_to', 'assignee_name',
            'created_at', 'updated_at', 'completed_at', 'is_overdue', 'tags',
            'comments', 'attachments', 'can_edit', 'can_delete', 'can_complete'
        ]
        read_only_fields = [
            'id', 'created_by', 'created_at', 'updated_at', 'completed_at',
            'status_display', 'priority_display', 'is_overdue', 'comments',
            'attachments'
        ]
    
    def get_assignee_name(self, obj):
        if obj.assigned_to:
            return obj.assigned_to.get_full_name() or obj.assigned_to.username
        return "Unassigned"
    
    def get_can_edit(self, obj):
        request = self.context.get('request')
        if request:
            return obj.created_by == request.user or obj.assigned_to == request.user
        return False
    
    def get_can_delete(self, obj):
        request = self.context.get('request')
        if request:
            return obj.created_by == request.user
        return False
    
    def get_can_complete(self, obj):
        request = self.context.get('request')
        if request:
            return obj.assigned_to == request.user or obj.created_by == request.user
        return False
    
    def create(self, validated_data):
        # Handle tags if present
        tags = validated_data.pop('tags', [])
        task = Task.objects.create(**validated_data)
        task.tags.set(tags)
        return task
    
    def update(self, instance, validated_data):
        # Handle tags if present
        tags = validated_data.pop('tags', None)
        if tags is not None:
            instance.tags.set(tags)
        
        # Update other fields
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        # If status is being updated to 'done', set completed_at
        if 'status' in validated_data and validated_data['status'] == 'done' and not instance.completed_at:
            from django.utils import timezone
            instance.completed_at = timezone.now()
        
        instance.save()
        return instance
