from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import datetime, timedelta
from .models import (
    Appointment, Service, StaffMember, 
    AppointmentNote, BusinessHours
)

User = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'full_name']
        read_only_fields = fields
    
    def get_full_name(self, obj):
        return obj.get_full_name()


class ServiceSerializer(serializers.ModelSerializer):
    duration_minutes = serializers.SerializerMethodField()
    
    class Meta:
        model = Service
        fields = [
            'id', 'name', 'description', 'duration', 
            'duration_minutes', 'price', 'color', 'image',
            'is_active', 'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_duration_minutes(self, obj):
        return obj.duration.total_seconds() // 60 if obj.duration else None


class StaffMemberSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    services = ServiceSerializer(many=True)
    full_name = serializers.SerializerMethodField()
    
    class Meta:
        model = StaffMember
        fields = [
            'id', 'user', 'services', 'bio', 
            'image', 'is_active', 'full_name',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_full_name(self, obj):
        return str(obj)


class AppointmentNoteSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    can_edit = serializers.SerializerMethodField()
    
    class Meta:
        model = AppointmentNote
        fields = ['id', 'content', 'author', 'created_at', 'updated_at', 'can_edit']
        read_only_fields = ['id', 'author', 'created_at', 'updated_at']
    
    def get_can_edit(self, obj):
        request = self.context.get('request')
        if not request:
            return False
        return obj.author == request.user or request.user.is_staff


class AppointmentSerializer(serializers.ModelSerializer):
    service = ServiceSerializer()
    staff_member = StaffMemberSerializer()
    client = UserSerializer()
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    can_edit = serializers.SerializerMethodField()
    can_cancel = serializers.SerializerMethodField()
    notes = AppointmentNoteSerializer(many=True, read_only=True)
    
    class Meta:
        model = Appointment
        fields = [
            'id', 'service', 'staff_member', 'client', 'start_time', 
            'end_time', 'status', 'status_display', 'client_name', 
            'client_email', 'client_phone', 'notes', 'created_at', 
            'updated_at', 'can_edit', 'can_cancel'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_can_edit(self, obj):
        request = self.context.get('request')
        if not request:
            return False
        return (
            request.user == obj.client or 
            request.user == obj.staff_member.user or
            request.user.is_staff
        )
    
    def get_can_cancel(self, obj):
        request = self.context.get('request')
        if not request:
            return False
        return (
            request.user == obj.client or 
            request.user.is_staff
        )


class BusinessHoursSerializer(serializers.ModelSerializer):
    day_display = serializers.CharField(source='get_day_display', read_only=True)
    
    class Meta:
        model = BusinessHours
        fields = [
            'id', 'day', 'day_display', 'is_open', 
            'open_time', 'close_time', 'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']


class AvailableSlotsSerializer(serializers.Serializer):
    date = serializers.DateField(required=True)
    service = serializers.PrimaryKeyRelatedField(
        queryset=Service.objects.filter(is_active=True),
        required=True
    )
    staff = serializers.PrimaryKeyRelatedField(
        queryset=StaffMember.objects.filter(is_active=True),
        required=False,
        allow_null=True
    )
    
    def validate_date(self, value):
        if value < timezone.now().date():
            raise serializers.ValidationError("Cannot book appointments in the past.")
        return value


class StaffMemberSimpleSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()
    
    class Meta:
        model = StaffMember
        fields = ['id', 'full_name', 'image']
        read_only_fields = fields
    
    def get_full_name(self, obj):
        return str(obj)


class ServiceSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields = ['id', 'name', 'duration', 'price']
        read_only_fields = fields


class AppointmentCreateSerializer(serializers.ModelSerializer):
    service = serializers.PrimaryKeyRelatedField(
        queryset=Service.objects.filter(is_active=True)
    )
    staff_member = serializers.PrimaryKeyRelatedField(
        queryset=StaffMember.objects.filter(is_active=True),
        required=False,
        allow_null=True
    )
    
    class Meta:
        model = Appointment
        fields = [
            'service', 'staff_member', 'start_time', 'end_time',
            'client_name', 'client_email', 'client_phone', 'notes'
        ]
    
    def validate(self, data):
        # Add any additional validation here
        return data
    
    def create(self, validated_data):
        # Set the client to the current user
        validated_data['client'] = self.context['request'].user
        return super().create(validated_data)


class AppointmentUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Appointment
        fields = [
            'service', 'staff_member', 'start_time', 'end_time',
            'status', 'client_name', 'client_email', 'client_phone', 'notes'
        ]
        read_only_fields = ['service']  # Don't allow changing service after creation
    
    def validate(self, data):
        # Add any additional validation here
        return data
