from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q, Count, Max
from django.http import JsonResponse
from django.utils import timezone
from .models import Chat, Message
from users.models import User, Teacher, Student


@login_required
def chat_list(request):
    """Список чатов пользователя с поиском"""
    user = request.user
    query = request.GET.get('q', '')

    # Получаем все чаты пользователя
    chats = user.chats.all().annotate(
        last_message_time=Max('messages__created_at')
    ).order_by('-last_message_time')

    # Поиск по чатам
    if query:
        chats = chats.filter(
            Q(name__icontains=query) |
            Q(participants__last_name__icontains=query) |
            Q(participants__first_name__icontains=query)
        ).distinct()

    # Для каждого чата получаем последнее сообщение и непрочитанные
    for chat in chats:
        chat.last_message = chat.messages.order_by('-created_at').first()
        chat.unread_count = chat.messages.filter(
            ~Q(sender=user),
            is_read=False
        ).count()
        # Получаем собеседников (кроме текущего пользователя)
        chat.other_participants = chat.participants.exclude(id=user.id)

    # Все пользователи для создания нового чата (без родителей)
    if user.role == 'student':
        users_for_chat = User.objects.filter(
            role__in=['teacher', 'admin', 'academic_staff']
        ).exclude(id=user.id)
    elif user.role == 'teacher':
        users_for_chat = User.objects.filter(
            role__in=['student', 'teacher', 'admin', 'academic_staff']
        ).exclude(id=user.id)
    elif user.role in ['admin', 'academic_staff']:
        users_for_chat = User.objects.filter(
            role__in=['student', 'teacher', 'admin', 'academic_staff']
        ).exclude(id=user.id)
    else:
        users_for_chat = User.objects.none()

    # Добавляем полное имя для каждого пользователя
    for u in users_for_chat:
        if u.role == 'teacher':
            try:
                teacher = u.teacher
                u.full_name = f"{teacher.last_name} {teacher.first_name} {teacher.middle_name or ''}".strip()
            except:
                u.full_name = u.email
        elif u.role == 'student':
            try:
                student = u.student
                u.full_name = f"{student.last_name} {student.first_name} {student.middle_name or ''}".strip()
            except:
                u.full_name = u.email
        else:
            u.full_name = u.email

    # Поиск пользователей для создания чата
    user_query = request.GET.get('user_search', '')
    if user_query:
        users_for_chat = users_for_chat.filter(
            Q(last_name__icontains=user_query) |
            Q(first_name__icontains=user_query) |
            Q(email__icontains=user_query)
        )

    context = {
        'chats': chats,
        'users_for_chat': users_for_chat[:20],
        'query': query,
        'user_query': user_query,
    }
    return render(request, 'chat_list.html', context)


@login_required
def create_chat(request):
    """Создание нового чата (личный или групповой)"""
    if request.method == 'POST':
        user_ids = request.POST.getlist('users')
        chat_type = request.POST.get('chat_type', 'private')
        chat_name = request.POST.get('name', '')

        if not user_ids:
            messages.error(request, 'Выберите хотя бы одного участника')
            return redirect('chat_list')

        # Добавляем текущего пользователя
        participant_ids = [int(request.user.id)] + [int(uid) for uid in user_ids]
        participant_ids = list(set(participant_ids))

        # Проверяем, существует ли уже такой чат
        if chat_type == 'private' and len(participant_ids) == 2:
            existing_chat = Chat.objects.filter(
                participants__id__in=participant_ids,
                is_group=False
            ).distinct().annotate(count=Count('participants')).filter(count=len(participant_ids))

            if existing_chat.exists():
                messages.info(request, 'Чат с этим пользователем уже существует')
                return redirect('chat_detail', chat_id=existing_chat.first().id)

        # Создаём новый чат
        chat = Chat.objects.create(
            name=chat_name if chat_type == 'group' else None,
            is_group=(chat_type == 'group'),
            created_by=request.user
        )
        chat.participants.set(participant_ids)

        messages.success(request, 'Чат создан')
        return redirect('chat_detail', chat_id=chat.id)

    return redirect('chat_list')


@login_required
def chat_detail(request, chat_id):
    """Детальный просмотр чата"""
    chat = get_object_or_404(Chat, id=chat_id, participants=request.user)

    # Отмечаем сообщения как прочитанные
    Message.objects.filter(chat=chat, is_read=False).exclude(sender=request.user).update(is_read=True)

    if request.method == 'POST':
        text = request.POST.get('message', '').strip()
        if text:
            Message.objects.create(
                chat=chat,
                sender=request.user,
                text=text
            )
            chat.updated_at = timezone.now()
            chat.save(update_fields=['updated_at'])

        return redirect('chat_detail', chat_id=chat.id)

    # Получаем все сообщения
    messages_list = chat.messages.order_by('created_at')

    # Получаем участников (с полными именами)
    participants = chat.participants.all()
    for p in participants:
        if p.role == 'teacher':
            try:
                teacher = p.teacher
                p.full_name = f"{teacher.last_name} {teacher.first_name} {teacher.middle_name or ''}".strip()
            except:
                p.full_name = p.email
        elif p.role == 'student':
            try:
                student = p.student
                p.full_name = f"{student.last_name} {student.first_name} {student.middle_name or ''}".strip()
            except:
                p.full_name = p.email
        else:
            p.full_name = p.email

    context = {
        'chat': chat,
        'messages': messages_list,
        'participants': participants,
    }
    return render(request, 'chat_detail.html', context)


@login_required
def delete_chat(request, chat_id):
    """Удаление чата (только для себя)"""
    chat = get_object_or_404(Chat, id=chat_id, participants=request.user)

    if request.method == 'POST':
        chat.participants.remove(request.user)

        if chat.participants.count() == 0:
            chat.delete()
            messages.success(request, 'Чат удалён')
        else:
            messages.success(request, 'Вы вышли из чата')

        return redirect('chat_list')

    return redirect('chat_detail', chat_id=chat.id)


@login_required
def get_user_info(request, user_id):
    """Получение информации о пользователе для создания чата"""
    user = get_object_or_404(User, id=user_id)

    if user.role == 'teacher':
        try:
            teacher = user.teacher
            full_name = f"{teacher.last_name} {teacher.first_name} {teacher.middle_name or ''}".strip()
        except:
            full_name = user.email
    elif user.role == 'student':
        try:
            student = user.student
            full_name = f"{student.last_name} {student.first_name} {student.middle_name or ''}".strip()
        except:
            full_name = user.email
    else:
        full_name = user.email

    return JsonResponse({
        'id': user.id,
        'full_name': full_name,
        'email': user.email,
        'role': user.role
    })


@login_required
def leave_chat(request, chat_id):
    """Выход из группового чата"""
    chat = get_object_or_404(Chat, id=chat_id, participants=request.user)

    if request.method == 'POST':
        chat.participants.remove(request.user)
        messages.success(request, 'Вы вышли из чата')

        if chat.participants.count() == 0:
            chat.delete()

        return redirect('chat_list')

    return redirect('chat_detail', chat_id=chat.id)