from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView, UpdateView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.db.models import Q
from .models import Group, GroupMember

class GroupsHubView(LoginRequiredMixin, ListView):
    model = Group
    template_name = 'groups/hub.html'
    context_object_name = 'discover_groups'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.request.user
        context['your_circles'] = Group.objects.filter(
            memberships__user=user, 
            memberships__status='active'
        ).distinct()
        
        # Simple recommendation based on intent (can be refined later)
        user_profile = getattr(user, 'profile', None)
        if user_profile:
            user_intents = user_profile.intents.all()
            context['recommended_groups'] = Group.objects.exclude(
                memberships__user=user
            ).filter(
                intent_type__in=[i.name.lower() for i in user_intents]
            ).distinct()[:3]
        
        return context

class GroupCreateView(LoginRequiredMixin, CreateView):
    model = Group
    template_name = 'groups/group_form.html'
    fields = [
        'name', 'description', 'group_type', 'intent_type', 
        'focus_game', 'visibility', 'capacity', 
        'location_scope', 'city', 'state', 'recurring_schedule', 'cover_image'
    ]
    success_url = reverse_lazy('groups:hub')

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        response = super().form_valid(form)
        # Automatically add creator as owner
        GroupMember.objects.create(
            group=self.object,
            user=self.request.user,
            role='owner',
            status='active'
        )
        return response

class GroupDetailView(LoginRequiredMixin, DetailView):
    model = Group
    template_name = 'groups/group_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.request.user
        context['is_member'] = self.object.memberships.filter(user=user, status='active').exists()
        context['is_pending'] = self.object.memberships.filter(user=user, status='pending').exists()
        context['membership'] = self.object.memberships.filter(user=user).first()
        context['active_members'] = self.object.memberships.filter(status='active')
        return context

class GroupUpdateView(LoginRequiredMixin, UpdateView):
    model = Group
    template_name = 'groups/group_form.html'
    fields = [
        'name', 'description', 'group_type', 'intent_type', 
        'focus_game', 'visibility', 'capacity', 
        'location_scope', 'city', 'state', 'recurring_schedule', 'cover_image'
    ]

    def get_queryset(self):
        return Group.objects.filter(memberships__user=self.request.user, memberships__role__in=['owner', 'moderator'])

    def get_success_url(self):
        return reverse_lazy('groups:detail', kwargs={'pk': self.object.pk})

class GroupMembersView(LoginRequiredMixin, DetailView):
    model = Group
    template_name = 'groups/group_members.html'

class GroupJoinView(LoginRequiredMixin, View):
    def post(self, request, pk):
        group = get_object_or_404(Group, pk=pk)
        
        # Check if already a member
        if group.memberships.filter(user=request.user).exists():
            return redirect('groups:detail', pk=pk)
        
        status = 'active'
        if group.visibility == 'private_request':
            status = 'pending'
        
        try:
            GroupMember.objects.create(
                group=group,
                user=request.user,
                status=status
            )
        except Exception as e:
            # Handle capacity error from model clean
            pass
            
        return redirect('groups:detail', pk=pk)

class GroupLeaveView(LoginRequiredMixin, View):
    def post(self, request, pk):
        membership = get_object_or_404(GroupMember, group_id=pk, user=request.user)
        if membership.role != 'owner':
            membership.delete()
        return redirect('groups:hub')

class GroupModerationView(LoginRequiredMixin, DetailView):
    model = Group
    template_name = 'groups/group_moderation.html'

    def get_queryset(self):
        return Group.objects.filter(memberships__user=self.request.user, memberships__role__in=['owner', 'moderator'])
