from django.db import models
from django.utils import timezone
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.conf import settings
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
import requests

from .models import User, AdminProfile, VendorProfile, BuyerProfile, OTP, EmailVerificationToken, Follow, EmailCampaign, VendorGalleryPhoto
from .serializers import (
    UserSerializer,
    AdminRegistrationSerializer,
    VendorRegistrationSerializer,
    BuyerRegistrationSerializer,
    LoginSerializer,
    VendorProfileSerializer,
    BuyerProfileSerializer,
    AdminProfileSerializer,
)
from .email_service import send_otp_email, send_email_verification, send_welcome_email, send_password_reset_otp_email, send_bulk_email


def get_tokens_for_user(user):
    """Generate JWT tokens for user"""
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }


class AdminRegistrationView(generics.CreateAPIView):
    """API endpoint for admin registration - only existing admins can create new admins"""
    serializer_class = AdminRegistrationSerializer
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        # Only admins can create other admins
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Only admins can create admin accounts'
            }, status=status.HTTP_403_FORBIDDEN)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        tokens = get_tokens_for_user(user)

        return Response({
            'success': True,
            'message': 'Admin registered successfully.',
            'data': {
                'user': UserSerializer(user).data,
                'tokens': tokens
            }
        }, status=status.HTTP_201_CREATED)


class VendorRegistrationView(generics.CreateAPIView):
    """API endpoint for vendor registration"""
    serializer_class = VendorRegistrationSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        tokens = get_tokens_for_user(user)
        vendor_profile = VendorProfile.objects.get(user=user)

        # Send welcome email
        try:
            send_welcome_email(user)
        except Exception as e:
            print(f"Failed to send welcome email: {e}")

        # Send welcome notification
        try:
            from notifications.models import Notification
            Notification.notify_welcome(user)
        except Exception as e:
            print(f"Failed to send welcome notification: {e}")

        return Response({
            'success': True,
            'message': 'Vendor registered successfully.',
            'data': {
                'user': UserSerializer(user).data,
                'vendor_profile': VendorProfileSerializer(vendor_profile).data,
                'tokens': tokens
            }
        }, status=status.HTTP_201_CREATED)


class BuyerRegistrationView(generics.CreateAPIView):
    """API endpoint for buyer registration"""
    serializer_class = BuyerRegistrationSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        tokens = get_tokens_for_user(user)
        buyer_profile = BuyerProfile.objects.get(user=user)

        # Send welcome email
        try:
            send_welcome_email(user)
        except Exception as e:
            print(f"Failed to send welcome email: {e}")

        # Send welcome notification
        try:
            from notifications.models import Notification
            Notification.notify_welcome(user)
        except Exception as e:
            print(f"Failed to send welcome notification: {e}")

        return Response({
            'success': True,
            'message': 'Buyer registered successfully.',
            'data': {
                'user': UserSerializer(user).data,
                'buyer_profile': BuyerProfileSerializer(buyer_profile).data,
                'tokens': tokens
            }
        }, status=status.HTTP_201_CREATED)


class LoginView(APIView):
    """API endpoint for user login - Step 1: Verify email + password, send OTP"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        password = request.data.get('password')

        if not email or not password:
            return Response({
                'success': False,
                'message': 'Email and password are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            if not user.check_password(password):
                return Response({
                    'success': False,
                    'message': 'Invalid email or password'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if not user.is_active:
                return Response({
                    'success': False,
                    'message': 'User account is disabled'
                }, status=status.HTTP_401_UNAUTHORIZED)

            # Generate and send OTP
            try:
                otp = OTP.generate_otp(user, otp_type='login')
                email_sent = send_otp_email(user, otp)
            except Exception as e:
                print(f"OTP/Email error: {e}")
                email_sent = False

            return Response({
                'success': True,
                'message': 'OTP sent to your email' if email_sent else 'Login verified but failed to send OTP email. Please try again.',
                'data': {
                    'email': email,
                    'email_sent': email_sent
                }
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Invalid email or password'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            print(f"Login error: {e}")
            return Response({
                'success': False,
                'message': 'An error occurred during login. Please try again.'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VerifyLoginOTPView(APIView):
    """API endpoint to verify login OTP - Step 2: Complete login"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        otp_code = request.data.get('otp_code')

        if not email or not otp_code:
            return Response({
                'success': False,
                'message': 'Email and OTP code are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            # Verify OTP
            is_valid, message = OTP.verify_otp(user, otp_code, otp_type='login')

            if not is_valid:
                return Response({
                    'success': False,
                    'message': message
                }, status=status.HTTP_400_BAD_REQUEST)

            # Generate tokens
            tokens = get_tokens_for_user(user)

            # Get profile based on user type
            profile_data = None
            try:
                if user.user_type == 'vendor':
                    profile = VendorProfile.objects.get(user=user)
                    profile_data = VendorProfileSerializer(profile).data
                elif user.user_type == 'buyer':
                    profile = BuyerProfile.objects.get(user=user)
                    profile_data = BuyerProfileSerializer(profile).data
                elif user.user_type == 'admin':
                    profile = AdminProfile.objects.get(user=user)
                    profile_data = AdminProfileSerializer(profile).data
            except (VendorProfile.DoesNotExist, BuyerProfile.DoesNotExist, AdminProfile.DoesNotExist):
                profile_data = None

            return Response({
                'success': True,
                'message': 'Login successful',
                'data': {
                    'user': UserSerializer(user).data,
                    'profile': profile_data,
                    'tokens': tokens
                }
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            print(f"OTP verify error: {e}")
            return Response({
                'success': False,
                'message': 'An error occurred during verification. Please try again.'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ResendLoginOTPView(APIView):
    """API endpoint to resend login OTP"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')

        if not email:
            return Response({
                'success': False,
                'message': 'Email is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            # Generate and send new OTP
            try:
                otp = OTP.generate_otp(user, otp_type='login')
                email_sent = send_otp_email(user, otp)
            except Exception as e:
                print(f"Resend OTP error: {e}")
                email_sent = False

            return Response({
                'success': True if email_sent else False,
                'message': 'OTP sent successfully' if email_sent else 'Failed to send OTP email. Please try again.',
                'data': {
                    'email_sent': email_sent
                }
            }, status=status.HTTP_200_OK if email_sent else status.HTTP_500_INTERNAL_SERVER_ERROR)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)


class VerifyEmailView(APIView):
    """API endpoint to verify email"""
    permission_classes = [AllowAny]

    def post(self, request):
        token = request.data.get('token')

        if not token:
            return Response({
                'success': False,
                'message': 'Verification token is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            email_token = EmailVerificationToken.objects.get(token=token)

            if not email_token.is_valid:
                return Response({
                    'success': False,
                    'message': 'Token has expired or already been used'
                }, status=status.HTTP_400_BAD_REQUEST)

            # Mark email as verified
            user = email_token.user
            user.is_email_verified = True
            user.save()

            # Mark token as used
            email_token.is_used = True
            email_token.save()

            return Response({
                'success': True,
                'message': 'Email verified successfully'
            }, status=status.HTTP_200_OK)

        except EmailVerificationToken.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Invalid verification token'
            }, status=status.HTTP_400_BAD_REQUEST)


class ResendVerificationEmailView(APIView):
    """API endpoint to resend verification email"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user

        if not user.email:
            return Response({
                'success': False,
                'message': 'No email address on file'
            }, status=status.HTTP_400_BAD_REQUEST)

        if user.is_email_verified:
            return Response({
                'success': False,
                'message': 'Email is already verified'
            }, status=status.HTTP_400_BAD_REQUEST)

        # Create new verification token
        token = EmailVerificationToken.objects.create(user=user)
        email_sent = send_email_verification(user, token)

        if email_sent:
            return Response({
                'success': True,
                'message': 'Verification email sent successfully'
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': 'Failed to send verification email'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserProfileView(APIView):
    """API endpoint to get and update current user profile"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def get(self, request):
        user = request.user

        # Get profile based on user type
        profile_data = None
        if user.user_type == 'vendor':
            try:
                profile = VendorProfile.objects.get(user=user)
                # Check subscription expiry and auto-downgrade
                if profile.is_upgraded:
                    try:
                        sub = profile.subscription
                        if sub.is_expired:
                            profile.is_upgraded = False
                            profile.save()
                            sub.is_active = False
                            sub.save()
                    except Exception:
                        pass
                profile_data = VendorProfileSerializer(profile, context={'request': request}).data
            except VendorProfile.DoesNotExist:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found. Please complete your vendor registration.'
                }, status=status.HTTP_404_NOT_FOUND)
        elif user.user_type == 'buyer':
            try:
                profile = BuyerProfile.objects.get(user=user)
                profile_data = BuyerProfileSerializer(profile, context={'request': request}).data
            except BuyerProfile.DoesNotExist:
                profile_data = None
        elif user.user_type == 'admin':
            try:
                profile = AdminProfile.objects.get(user=user)
                profile_data = AdminProfileSerializer(profile, context={'request': request}).data
            except AdminProfile.DoesNotExist:
                profile_data = None

        return Response({
            'success': True,
            'data': {
                'user': UserSerializer(user, context={'request': request}).data,
                'profile': profile_data
            }
        }, status=status.HTTP_200_OK)

    def patch(self, request):
        user = request.user

        # Update user fields if provided
        if 'full_name' in request.data:
            user.full_name = request.data['full_name']
        if 'profile_photo' in request.FILES:
            user.profile_photo = request.FILES['profile_photo']
        user.save()

        # Update profile based on user type
        if user.user_type == 'vendor':
            try:
                profile = VendorProfile.objects.get(user=user)
                if 'shop_name' in request.data:
                    profile.shop_name = request.data['shop_name']
                if 'shop_category' in request.data:
                    profile.shop_category = request.data['shop_category']
                if 'bio' in request.data:
                    profile.bio = request.data['bio']
                if 'town_area' in request.data:
                    profile.town_area = request.data['town_area']
                if 'whatsapp_number' in request.data:
                    profile.whatsapp_number = request.data['whatsapp_number']
                if 'shop_logo' in request.FILES:
                    profile.shop_logo = request.FILES['shop_logo']
                profile.save()
                profile_data = VendorProfileSerializer(profile, context={'request': request}).data
            except VendorProfile.DoesNotExist:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found'
                }, status=status.HTTP_404_NOT_FOUND)
        elif user.user_type == 'buyer':
            profile = BuyerProfile.objects.get(user=user)
            profile_data = BuyerProfileSerializer(profile, context={'request': request}).data
        else:
            profile_data = None

        return Response({
            'success': True,
            'message': 'Profile updated successfully',
            'data': {
                'user': UserSerializer(user, context={'request': request}).data,
                'profile': profile_data
            }
        }, status=status.HTTP_200_OK)


class ChangePasswordView(APIView):
    """API endpoint for changing password"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        current_password = request.data.get('current_password', '')
        new_password = request.data.get('new_password', '')
        confirm_password = request.data.get('confirm_password', '')

        if not current_password or not new_password or not confirm_password:
            return Response({
                'success': False,
                'message': 'All fields are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not request.user.check_password(current_password):
            return Response({
                'success': False,
                'message': 'Current password is incorrect'
            }, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response({
                'success': False,
                'message': 'New passwords do not match'
            }, status=status.HTTP_400_BAD_REQUEST)

        if len(new_password) < 8:
            return Response({
                'success': False,
                'message': 'Password must be at least 8 characters'
            }, status=status.HTTP_400_BAD_REQUEST)

        request.user.set_password(new_password)
        request.user.save()

        return Response({
            'success': True,
            'message': 'Password changed successfully'
        }, status=status.HTTP_200_OK)


class ForgotPasswordView(APIView):
    """API endpoint for forgot password - sends OTP to email"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')

        if not email:
            return Response({
                'success': False,
                'message': 'Email is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            # Generate and send OTP
            try:
                otp = OTP.generate_otp(user, otp_type='password_reset')
                email_sent = send_password_reset_otp_email(user, otp)
            except Exception as e:
                print(f"Password reset OTP error: {e}")
                email_sent = False

            if email_sent:
                return Response({
                    'success': True,
                    'message': 'Password reset code sent to your email',
                    'data': {'email': email}
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    'success': False,
                    'message': 'Failed to send reset code. Please try again.'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except User.DoesNotExist:
            # Return success even if user doesn't exist to prevent email enumeration
            return Response({
                'success': True,
                'message': 'If an account with that email exists, a reset code has been sent.'
            }, status=status.HTTP_200_OK)


class VerifyForgotPasswordOTPView(APIView):
    """API endpoint to verify forgot password OTP"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        otp_code = request.data.get('otp_code')

        if not email or not otp_code:
            return Response({
                'success': False,
                'message': 'Email and OTP code are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            is_valid, message = OTP.verify_otp(user, otp_code, otp_type='password_reset')

            if not is_valid:
                return Response({
                    'success': False,
                    'message': message
                }, status=status.HTTP_400_BAD_REQUEST)

            # Generate a new OTP for the reset step so the original can't be reused
            new_otp = OTP.generate_otp(user, otp_type='password_reset')

            return Response({
                'success': True,
                'message': 'OTP verified successfully',
                'data': {'otp_code': new_otp.otp_code}
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)


class ResetPasswordView(APIView):
    """API endpoint to reset password with OTP"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        otp_code = request.data.get('otp_code')
        new_password = request.data.get('new_password')
        confirm_password = request.data.get('confirm_password')

        if not all([email, otp_code, new_password, confirm_password]):
            return Response({
                'success': False,
                'message': 'All fields are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response({
                'success': False,
                'message': 'Passwords do not match'
            }, status=status.HTTP_400_BAD_REQUEST)

        if len(new_password) < 8:
            return Response({
                'success': False,
                'message': 'Password must be at least 8 characters'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(email=email)

            is_valid, message = OTP.verify_otp(user, otp_code, otp_type='password_reset')

            if not is_valid:
                return Response({
                    'success': False,
                    'message': message
                }, status=status.HTTP_400_BAD_REQUEST)

            user.set_password(new_password)
            user.save()

            return Response({
                'success': True,
                'message': 'Password reset successfully'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)


class LogoutView(APIView):
    """API endpoint for user logout"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            refresh_token = request.data.get('refresh')
            if refresh_token:
                token = RefreshToken(refresh_token)
                token.blacklist()
            return Response({
                'success': True,
                'message': 'Logged out successfully'
            }, status=status.HTTP_200_OK)
        except Exception:
            return Response({
                'success': True,
                'message': 'Logged out successfully'
            }, status=status.HTTP_200_OK)


class CheckPhoneView(APIView):
    """API endpoint to check if phone number is already registered"""
    permission_classes = [AllowAny]

    def post(self, request):
        phone_number = request.data.get('phone_number')
        if not phone_number:
            return Response({
                'success': False,
                'message': 'Phone number is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        exists = User.objects.filter(phone_number=phone_number).exists()
        return Response({
            'success': True,
            'exists': exists
        }, status=status.HTTP_200_OK)


class CheckEmailView(APIView):
    """API endpoint to check if email is already registered"""
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get('email')
        if not email:
            return Response({
                'success': False,
                'message': 'Email is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        exists = User.objects.filter(email=email).exists()
        return Response({
            'success': True,
            'exists': exists
        }, status=status.HTTP_200_OK)


class FollowVendorView(APIView):
    """API endpoint for buyers to follow a vendor"""
    permission_classes = [IsAuthenticated]

    def post(self, request, vendor_id):
        if request.user.user_type != 'buyer':
            return Response({
                'success': False,
                'message': 'Only buyers can follow vendors'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            vendor = User.objects.get(id=vendor_id, user_type='vendor')

            # Check if already following
            if Follow.objects.filter(buyer=request.user, vendor=vendor).exists():
                return Response({
                    'success': False,
                    'message': 'You are already following this vendor'
                }, status=status.HTTP_400_BAD_REQUEST)

            # Create follow relationship
            Follow.objects.create(buyer=request.user, vendor=vendor)

            # Update counts
            vendor.vendor_profile.total_followers += 1
            vendor.vendor_profile.save()

            if hasattr(request.user, 'buyer_profile'):
                request.user.buyer_profile.following_count += 1
                request.user.buyer_profile.save()

            return Response({
                'success': True,
                'message': f'You are now following {vendor.vendor_profile.shop_name}'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Vendor not found'
            }, status=status.HTTP_404_NOT_FOUND)


class UnfollowVendorView(APIView):
    """API endpoint for buyers to unfollow a vendor"""
    permission_classes = [IsAuthenticated]

    def delete(self, request, vendor_id):
        if request.user.user_type != 'buyer':
            return Response({
                'success': False,
                'message': 'Only buyers can unfollow vendors'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            vendor = User.objects.get(id=vendor_id, user_type='vendor')

            follow = Follow.objects.filter(buyer=request.user, vendor=vendor).first()
            if not follow:
                return Response({
                    'success': False,
                    'message': 'You are not following this vendor'
                }, status=status.HTTP_400_BAD_REQUEST)

            # Delete follow relationship
            follow.delete()

            # Update counts
            vendor.vendor_profile.total_followers = max(0, vendor.vendor_profile.total_followers - 1)
            vendor.vendor_profile.save()

            if hasattr(request.user, 'buyer_profile'):
                request.user.buyer_profile.following_count = max(0, request.user.buyer_profile.following_count - 1)
                request.user.buyer_profile.save()

            return Response({
                'success': True,
                'message': f'You have unfollowed {vendor.vendor_profile.shop_name}'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Vendor not found'
            }, status=status.HTTP_404_NOT_FOUND)


class FollowingListView(APIView):
    """API endpoint to list vendors a buyer is following"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'buyer':
            return Response({
                'success': False,
                'message': 'Only buyers can view following list'
            }, status=status.HTTP_403_FORBIDDEN)

        follows = Follow.objects.filter(buyer=request.user).select_related('vendor__vendor_profile')

        following_list = []
        for follow in follows:
            vendor = follow.vendor
            if hasattr(vendor, 'vendor_profile'):
                vp = vendor.vendor_profile
                following_list.append({
                    'id': follow.id,
                    'vendor_id': vendor.id,
                    'slug': vp.slug,
                    'shop_name': vp.shop_name,
                    'shop_logo': request.build_absolute_uri(vp.shop_logo.url) if vp.shop_logo else None,
                    'shop_category': vp.shop_category,
                    'town_area': vp.town_area or '',
                    'county': vendor.county,
                    'rating': float(vp.rating) if vp.rating else 0.0,
                    'total_products': vp.total_products,
                    'is_verified_vendor': vp.is_verified_vendor,
                    'followed_at': follow.created_at
                })

        return Response({
            'success': True,
            'data': following_list
        }, status=status.HTTP_200_OK)


class FollowersListView(APIView):
    """API endpoint for vendors to see their followers"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'vendor':
            return Response({
                'success': False,
                'message': 'Only vendors can view their followers'
            }, status=status.HTTP_403_FORBIDDEN)

        follows = Follow.objects.filter(vendor=request.user).select_related('buyer')

        followers_list = []
        for follow in follows:
            buyer = follow.buyer
            photo_url = None
            if buyer.profile_photo:
                photo_url = request.build_absolute_uri(buyer.profile_photo.url)
            followers_list.append({
                'buyer_id': buyer.id,
                'full_name': buyer.full_name,
                'profile_photo': photo_url,
                'county': buyer.county,
                'followed_at': follow.created_at
            })

        return Response({
            'success': True,
            'data': followers_list
        }, status=status.HTTP_200_OK)


class CheckFollowStatusView(APIView):
    """API endpoint to check if buyer is following a vendor"""
    permission_classes = [IsAuthenticated]

    def get(self, request, vendor_id):
        if request.user.user_type != 'buyer':
            return Response({
                'success': True,
                'is_following': False
            }, status=status.HTTP_200_OK)

        is_following = Follow.objects.filter(
            buyer=request.user,
            vendor_id=vendor_id
        ).exists()

        return Response({
            'success': True,
            'is_following': is_following
        }, status=status.HTTP_200_OK)


class VendorsPublicListView(APIView):
    """API endpoint to list all public vendors"""
    permission_classes = [AllowAny]

    def get(self, request):
        search = request.query_params.get('search', None)
        category = request.query_params.get('category', None)
        county = request.query_params.get('county', None)
        verified = request.query_params.get('verified', '').lower() in ('true', '1', 'yes')
        page = int(request.query_params.get('page', 1))
        limit = int(request.query_params.get('limit', 20))

        vendors = VendorProfile.objects.select_related('user').filter(
            user__is_active=True
        ).order_by('-total_followers', '-rating')

        if verified:
            vendors = vendors.filter(is_verified_vendor=True)

        if search:
            vendors = vendors.filter(
                models.Q(shop_name__icontains=search) |
                models.Q(bio__icontains=search) |
                models.Q(user__full_name__icontains=search)
            )

        if category:
            vendors = vendors.filter(shop_category=category)

        if county:
            vendors = vendors.filter(user__county=county)

        total = vendors.count()
        start = (page - 1) * limit
        end = start + limit
        vendors = vendors[start:end]

        from django.db.models import Avg, Count
        from products.models import Product, Review

        data = []
        for v in vendors:
            active_count = Product.objects.filter(vendor=v, status='active').count()
            review_agg = Review.objects.filter(product__vendor=v).aggregate(
                avg_rating=Avg('rating'), review_count=Count('id')
            )
            avg_rating = round(float(review_agg['avg_rating']), 1) if review_agg['avg_rating'] else 0.0
            data.append({
                'id': v.id,
                'user_id': v.user.id,
                'slug': v.slug,
                'shop_name': v.shop_name,
                'shop_logo': request.build_absolute_uri(v.shop_logo.url) if v.shop_logo else None,
                'shop_category': v.shop_category,
                'bio': v.bio,
                'county': v.user.county,
                'town_area': v.town_area,
                'total_products': active_count,
                'total_followers': v.total_followers,
                'rating': avg_rating,
                'rating_count': review_agg['review_count'],
                'is_verified_vendor': v.is_verified_vendor,
                'is_upgraded': v.is_upgraded,
                'whatsapp_number': v.whatsapp_number,
            })

        return Response({
            'success': True,
            'data': data,
            'pagination': {
                'total': total,
                'page': page,
                'limit': limit,
                'pages': (total + limit - 1) // limit
            }
        }, status=status.HTTP_200_OK)


class VendorPublicProfileView(APIView):
    """API endpoint to get public vendor profile by ID or slug"""
    permission_classes = [AllowAny]

    def get(self, request, vendor_slug):
        try:
            # Try to find by slug first, then by ID
            vendor_profile = None
            if vendor_slug.isdigit():
                vendor = User.objects.get(id=int(vendor_slug), user_type='vendor')
                vendor_profile = vendor.vendor_profile
            else:
                vendor_profile = VendorProfile.objects.select_related('user').get(slug=vendor_slug)
                vendor = vendor_profile.user

            # Check follow status if user is authenticated buyer
            is_following = False
            if request.user.is_authenticated and request.user.user_type == 'buyer':
                is_following = Follow.objects.filter(
                    buyer=request.user,
                    vendor=vendor
                ).exists()

            shop_logo_url = None
            if vendor_profile.shop_logo:
                shop_logo_url = request.build_absolute_uri(vendor_profile.shop_logo.url)

            from django.db.models import Avg, Count
            from products.models import Product, Review

            active_count = Product.objects.filter(vendor=vendor_profile, status__in=['active', 'coming_soon']).count()
            review_agg = Review.objects.filter(product__vendor=vendor_profile).aggregate(
                avg_rating=Avg('rating'), review_count=Count('id')
            )
            avg_rating = round(float(review_agg['avg_rating']), 1) if review_agg['avg_rating'] else 0.0

            # Determine AI chat availability
            has_ai_chat = False
            if vendor_profile.is_upgraded:
                try:
                    has_ai_chat = vendor_profile.ai_config.is_active
                except Exception:
                    has_ai_chat = False

            # Check if vendor has active M-Pesa credentials
            has_mpesa = False
            try:
                mpesa_creds = vendor_profile.mpesa_credentials
                has_mpesa = mpesa_creds and mpesa_creds.is_active
            except Exception:
                pass

            return Response({
                'success': True,
                'data': {
                    'vendor_id': vendor.id,
                    'slug': vendor_profile.slug,
                    'shop_name': vendor_profile.shop_name,
                    'shop_logo': shop_logo_url,
                    'shop_category': vendor_profile.shop_category,
                    'bio': vendor_profile.bio,
                    'county': vendor.county,
                    'town_area': vendor_profile.town_area,
                    'total_products': active_count,
                    'total_followers': vendor_profile.total_followers,
                    'rating': avg_rating,
                    'rating_count': review_agg['review_count'],
                    'is_verified_vendor': vendor_profile.is_verified_vendor,
                    'is_upgraded': vendor_profile.is_upgraded,
                    'is_following': is_following,
                    'whatsapp_number': vendor_profile.whatsapp_number,
                    'has_ai_chat': has_ai_chat,
                    'has_mpesa': has_mpesa,
                    'business_hours': vendor_profile.business_hours,
                    'gallery_photos': [{
                        'id': p.id,
                        'image_url': request.build_absolute_uri(p.image.url),
                    } for p in vendor_profile.gallery_photos.all()],
                }
            }, status=status.HTTP_200_OK)

        except (User.DoesNotExist, VendorProfile.DoesNotExist):
            return Response({
                'success': False,
                'message': 'Vendor not found'
            }, status=status.HTTP_404_NOT_FOUND)


# ============== BUSINESS HOURS & GALLERY VIEWS ==============

import re

class VendorBusinessHoursView(APIView):
    """GET and PUT business hours for the authenticated vendor"""
    permission_classes = [IsAuthenticated]

    VALID_DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
    VALID_STATUSES = ['closed', 'open_24hrs', 'custom']
    TIME_RE = re.compile(r'^\d{2}:\d{2}$')

    def get(self, request):
        if request.user.user_type != 'vendor':
            return Response({'success': False, 'message': 'Vendor access required'}, status=status.HTTP_403_FORBIDDEN)
        vendor = request.user.vendor_profile
        return Response({'success': True, 'data': vendor.business_hours})

    def put(self, request):
        if request.user.user_type != 'vendor':
            return Response({'success': False, 'message': 'Vendor access required'}, status=status.HTTP_403_FORBIDDEN)

        hours = request.data
        if not isinstance(hours, dict):
            return Response({'success': False, 'message': 'Invalid format'}, status=status.HTTP_400_BAD_REQUEST)

        for day in self.VALID_DAYS:
            if day not in hours:
                return Response({'success': False, 'message': f'Missing day: {day}'}, status=status.HTTP_400_BAD_REQUEST)
            entry = hours[day]
            if not isinstance(entry, dict) or 'status' not in entry:
                return Response({'success': False, 'message': f'Invalid entry for {day}'}, status=status.HTTP_400_BAD_REQUEST)
            if entry['status'] not in self.VALID_STATUSES:
                return Response({'success': False, 'message': f'Invalid status for {day}'}, status=status.HTTP_400_BAD_REQUEST)
            if entry['status'] == 'custom':
                open_t = entry.get('open')
                close_t = entry.get('close')
                if not open_t or not close_t or not self.TIME_RE.match(open_t) or not self.TIME_RE.match(close_t):
                    return Response({'success': False, 'message': f'Invalid time for {day}. Use HH:MM format.'}, status=status.HTTP_400_BAD_REQUEST)

        vendor = request.user.vendor_profile
        vendor.business_hours = hours
        vendor.save(update_fields=['business_hours'])
        return Response({'success': True, 'message': 'Business hours updated', 'data': vendor.business_hours})


class VendorGalleryView(APIView):
    """GET gallery photos, POST to upload new photos"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def get(self, request):
        if request.user.user_type != 'vendor':
            return Response({'success': False, 'message': 'Vendor access required'}, status=status.HTTP_403_FORBIDDEN)
        vendor = request.user.vendor_profile
        photos = vendor.gallery_photos.all()
        data = [{
            'id': p.id,
            'image_url': request.build_absolute_uri(p.image.url),
            'created_at': p.created_at.isoformat(),
        } for p in photos]
        return Response({'success': True, 'data': data})

    def post(self, request):
        if request.user.user_type != 'vendor':
            return Response({'success': False, 'message': 'Vendor access required'}, status=status.HTTP_403_FORBIDDEN)

        vendor = request.user.vendor_profile
        files = request.FILES.getlist('photos')
        if not files:
            return Response({'success': False, 'message': 'No photos provided'}, status=status.HTTP_400_BAD_REQUEST)

        existing_count = vendor.gallery_photos.count()
        if existing_count + len(files) > 5:
            return Response({
                'success': False,
                'message': f'Maximum 5 gallery photos allowed. You have {existing_count}, trying to add {len(files)}.'
            }, status=status.HTTP_400_BAD_REQUEST)

        for f in files:
            if f.size > 1024 * 1024:
                return Response({
                    'success': False,
                    'message': f'File "{f.name}" exceeds 1MB limit ({f.size // 1024}KB).'
                }, status=status.HTTP_400_BAD_REQUEST)

        created = []
        for f in files:
            photo = VendorGalleryPhoto.objects.create(vendor=vendor, image=f)
            created.append({
                'id': photo.id,
                'image_url': request.build_absolute_uri(photo.image.url),
                'created_at': photo.created_at.isoformat(),
            })

        return Response({'success': True, 'message': f'{len(created)} photo(s) uploaded', 'data': created}, status=status.HTTP_201_CREATED)


class VendorGalleryPhotoDetailView(APIView):
    """DELETE a single gallery photo"""
    permission_classes = [IsAuthenticated]

    def delete(self, request, photo_id):
        if request.user.user_type != 'vendor':
            return Response({'success': False, 'message': 'Vendor access required'}, status=status.HTTP_403_FORBIDDEN)

        vendor = request.user.vendor_profile
        try:
            photo = VendorGalleryPhoto.objects.get(id=photo_id, vendor=vendor)
        except VendorGalleryPhoto.DoesNotExist:
            return Response({'success': False, 'message': 'Photo not found'}, status=status.HTTP_404_NOT_FOUND)

        photo.image.delete(save=False)
        photo.delete()
        return Response({'success': True, 'message': 'Photo deleted'})


# ============== ADMIN MANAGEMENT VIEWS ==============

class AdminUsersListView(APIView):
    """Admin view to list all users"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        # Get query parameters
        user_type = request.query_params.get('type', None)
        search = request.query_params.get('search', None)
        page = int(request.query_params.get('page', 1))
        limit = int(request.query_params.get('limit', 20))

        users = User.objects.all().order_by('-created_at')

        if user_type:
            users = users.filter(user_type=user_type)

        if search:
            users = users.filter(
                models.Q(full_name__icontains=search) |
                models.Q(email__icontains=search) |
                models.Q(phone_number__icontains=search)
            )

        total = users.count()
        start = (page - 1) * limit
        end = start + limit
        users = users[start:end]

        data = [{
            'id': u.id,
            'full_name': u.full_name,
            'email': u.email,
            'phone_number': u.phone_number,
            'user_type': u.user_type,
            'county': u.county,
            'is_active': u.is_active,
            'is_email_verified': u.is_email_verified,
            'created_at': u.created_at,
            'profile_photo': request.build_absolute_uri(u.profile_photo.url) if u.profile_photo else None,
        } for u in users]

        return Response({
            'success': True,
            'data': data,
            'pagination': {
                'total': total,
                'page': page,
                'limit': limit,
                'pages': (total + limit - 1) // limit
            }
        }, status=status.HTTP_200_OK)


class AdminUserDetailView(APIView):
    """Admin view to get/update/delete a user"""
    permission_classes = [IsAuthenticated]

    def get(self, request, user_id):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            user = User.objects.get(id=user_id)
            data = {
                'id': user.id,
                'full_name': user.full_name,
                'email': user.email,
                'phone_number': user.phone_number,
                'user_type': user.user_type,
                'county': user.county,
                'is_active': user.is_active,
                'is_email_verified': user.is_email_verified,
                'created_at': user.created_at,
                'profile_photo': request.build_absolute_uri(user.profile_photo.url) if user.profile_photo else None,
            }

            # Add profile data based on user type
            if user.user_type == 'vendor' and hasattr(user, 'vendor_profile'):
                vp = user.vendor_profile
                data['vendor_profile'] = {
                    'shop_name': vp.shop_name,
                    'shop_category': vp.shop_category,
                    'bio': vp.bio,
                    'town_area': vp.town_area,
                    'total_products': vp.total_products,
                    'total_followers': vp.total_followers,
                    'total_sales': vp.total_sales,
                    'rating': float(vp.rating),
                    'is_upgraded': vp.is_upgraded,
                    'is_verified_vendor': vp.is_verified_vendor,
                }
            elif user.user_type == 'buyer' and hasattr(user, 'buyer_profile'):
                bp = user.buyer_profile
                data['buyer_profile'] = {
                    'bio': bp.bio,
                    'following_count': bp.following_count,
                }

            return Response({
                'success': True,
                'data': data
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)

    def patch(self, request, user_id):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            user = User.objects.get(id=user_id)

            # Update allowed fields
            if 'is_active' in request.data:
                user.is_active = request.data['is_active']
            if 'is_email_verified' in request.data:
                user.is_email_verified = request.data['is_email_verified']

            user.save()

            return Response({
                'success': True,
                'message': 'User updated successfully'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, user_id):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            user = User.objects.get(id=user_id)

            # Prevent self-deletion
            if user.id == request.user.id:
                return Response({
                    'success': False,
                    'message': 'Cannot delete your own account'
                }, status=status.HTTP_400_BAD_REQUEST)

            user.delete()

            return Response({
                'success': True,
                'message': 'User deleted successfully'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'User not found'
            }, status=status.HTTP_404_NOT_FOUND)


class AdminVendorsListView(APIView):
    """Admin view to list all vendors with their profiles"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        search = request.query_params.get('search', None)
        is_upgraded = request.query_params.get('is_upgraded', None)
        is_verified = request.query_params.get('is_verified', None)
        page = int(request.query_params.get('page', 1))
        limit = int(request.query_params.get('limit', 20))

        vendors = VendorProfile.objects.select_related('user').order_by('-user__created_at')

        if search:
            vendors = vendors.filter(
                models.Q(shop_name__icontains=search) |
                models.Q(user__full_name__icontains=search) |
                models.Q(user__email__icontains=search)
            )

        if is_upgraded is not None:
            vendors = vendors.filter(is_upgraded=is_upgraded.lower() == 'true')

        if is_verified is not None:
            vendors = vendors.filter(is_verified_vendor=is_verified.lower() == 'true')

        total = vendors.count()
        start = (page - 1) * limit
        end = start + limit
        vendors = vendors[start:end]

        data = [{
            'id': v.user.id,
            'full_name': v.user.full_name,
            'email': v.user.email,
            'phone_number': v.user.phone_number,
            'shop_name': v.shop_name,
            'shop_category': v.shop_category,
            'shop_logo': request.build_absolute_uri(v.shop_logo.url) if v.shop_logo else None,
            'county': v.user.county,
            'town_area': v.town_area,
            'total_products': v.total_products,
            'total_followers': v.total_followers,
            'total_sales': v.total_sales,
            'rating': float(v.rating),
            'is_upgraded': v.is_upgraded,
            'is_verified_vendor': v.is_verified_vendor,
            'is_active': v.user.is_active,
            'created_at': v.user.created_at,
        } for v in vendors]

        return Response({
            'success': True,
            'data': data,
            'pagination': {
                'total': total,
                'page': page,
                'limit': limit,
                'pages': (total + limit - 1) // limit
            }
        }, status=status.HTTP_200_OK)


class AdminVendorDetailView(APIView):
    """Admin view to manage a specific vendor"""
    permission_classes = [IsAuthenticated]

    def patch(self, request, vendor_id):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            vendor = User.objects.get(id=vendor_id, user_type='vendor')
            vendor_profile = vendor.vendor_profile

            # Update allowed fields
            if 'is_verified_vendor' in request.data:
                vendor_profile.is_verified_vendor = request.data['is_verified_vendor']
            if 'is_upgraded' in request.data:
                is_upgraded = request.data['is_upgraded']
                vendor_profile.is_upgraded = is_upgraded

                # If marking as Pro with a duration, create/update subscription
                pro_months = request.data.get('pro_months')
                if is_upgraded and pro_months:
                    from payments.models import VendorSubscription
                    from django.utils import timezone
                    from datetime import timedelta

                    pro_months = int(pro_months)
                    now = timezone.now()
                    expires_at = now + timedelta(days=30 * pro_months)

                    sub, created = VendorSubscription.objects.update_or_create(
                        vendor=vendor_profile,
                        defaults={
                            'plan_type': 'admin',
                            'is_active': True,
                            'expires_at': expires_at,
                        }
                    )
                    # auto_now_add prevents normal update of started_at
                    VendorSubscription.objects.filter(pk=sub.pk).update(started_at=now)

                # If revoking Pro, deactivate subscription
                if not is_upgraded:
                    from payments.models import VendorSubscription
                    VendorSubscription.objects.filter(vendor=vendor_profile).update(is_active=False)

            if 'is_active' in request.data:
                vendor.is_active = request.data['is_active']

            vendor.save()
            vendor_profile.save()

            return Response({
                'success': True,
                'message': 'Vendor updated successfully'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Vendor not found'
            }, status=status.HTTP_404_NOT_FOUND)


class AdminStatsView(APIView):
    """Admin view to get dashboard statistics"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        from django.db.models import Sum, Count
        from django.db.models.functions import TruncDate
        from payments.models import Payment
        from products.models import Product
        from datetime import timedelta

        today = timezone.now().date()
        last_month = today - timedelta(days=30)
        previous_month = last_month - timedelta(days=30)

        # Basic counts
        total_users = User.objects.count()
        total_vendors = User.objects.filter(user_type='vendor').count()
        total_buyers = User.objects.filter(user_type='buyer').count()
        upgraded_vendors = VendorProfile.objects.filter(is_upgraded=True).count()
        verified_vendors = VendorProfile.objects.filter(is_verified_vendor=True).count()
        total_products = Product.objects.filter(is_available=True).count()

        # Today's stats
        users_today = User.objects.filter(created_at__date=today).count()
        products_today = Product.objects.filter(created_at__date=today).count()

        # Payment stats
        total_revenue = Payment.objects.filter(status='success').aggregate(
            total=Sum('amount')
        )['total'] or 0

        # This month's revenue
        this_month_revenue = Payment.objects.filter(
            status='success',
            created_at__date__gte=last_month
        ).aggregate(total=Sum('amount'))['total'] or 0

        # Previous month's revenue for comparison
        prev_month_revenue = Payment.objects.filter(
            status='success',
            created_at__date__gte=previous_month,
            created_at__date__lt=last_month
        ).aggregate(total=Sum('amount'))['total'] or 0

        # Calculate percentage changes
        revenue_change = 0
        if prev_month_revenue > 0:
            revenue_change = ((this_month_revenue - prev_month_revenue) / prev_month_revenue) * 100

        # Users change (this month vs last month)
        users_this_month = User.objects.filter(created_at__date__gte=last_month).count()
        users_last_month = User.objects.filter(
            created_at__date__gte=previous_month,
            created_at__date__lt=last_month
        ).count()
        users_change = 0
        if users_last_month > 0:
            users_change = ((users_this_month - users_last_month) / users_last_month) * 100

        # Vendors change
        vendors_this_month = User.objects.filter(user_type='vendor', created_at__date__gte=last_month).count()
        vendors_last_month = User.objects.filter(
            user_type='vendor',
            created_at__date__gte=previous_month,
            created_at__date__lt=last_month
        ).count()
        vendors_change = 0
        if vendors_last_month > 0:
            vendors_change = ((vendors_this_month - vendors_last_month) / vendors_last_month) * 100

        # Products change
        products_this_month = Product.objects.filter(created_at__date__gte=last_month).count()
        products_last_month = Product.objects.filter(
            created_at__date__gte=previous_month,
            created_at__date__lt=last_month
        ).count()
        products_change = 0
        if products_last_month > 0:
            products_change = ((products_this_month - products_last_month) / products_last_month) * 100

        # Recent subscriptions/payments
        recent_payments = Payment.objects.filter(
            status='success'
        ).select_related('user').order_by('-created_at')[:10]

        recent_subscriptions = []
        for payment in recent_payments:
            vendor_name = "Unknown"
            if hasattr(payment.user, 'vendor_profile'):
                vendor_name = payment.user.vendor_profile.shop_name or payment.user.full_name

            # Calculate relative date
            days_ago = (today - payment.created_at.date()).days
            if days_ago == 0:
                date_str = "Today"
            elif days_ago == 1:
                date_str = "Yesterday"
            elif days_ago < 7:
                date_str = f"{days_ago} days ago"
            else:
                date_str = payment.created_at.strftime("%b %d")

            recent_subscriptions.append({
                'id': f"SUB{payment.id:03d}",
                'vendor': vendor_name,
                'plan': payment.payment_type.replace('_', ' ').title() if payment.payment_type else 'Pro',
                'amount': float(payment.amount),
                'status': 'active' if (hasattr(payment.user, 'vendor_profile') and payment.user.vendor_profile.is_upgraded) else 'expired',
                'date': date_str,
            })

        # Top vendors by followers (Follow.vendor points to User, not VendorProfile)
        top_vendors = VendorProfile.objects.select_related('user').annotate(
            followers_count=Count('user__followers')
        ).order_by('-followers_count')[:4]

        top_vendors_data = []
        for vendor in top_vendors:
            top_vendors_data.append({
                'name': vendor.shop_name or 'Unnamed Shop',
                'followers': vendor.followers_count,
                'products': Product.objects.filter(vendor=vendor, is_available=True).count(),
                'rating': float(vendor.rating) if vendor.rating else 0,
                'image': request.build_absolute_uri(vendor.shop_logo.url) if vendor.shop_logo else None,
            })

        return Response({
            'success': True,
            'data': {
                'total_users': total_users,
                'total_vendors': total_vendors,
                'total_buyers': total_buyers,
                'upgraded_vendors': upgraded_vendors,
                'verified_vendors': verified_vendors,
                'total_revenue': float(total_revenue),
                'total_products': total_products,
                'users_today': users_today,
                'products_today': products_today,
                'revenue_change': round(revenue_change, 1),
                'users_change': round(users_change, 1),
                'vendors_change': round(vendors_change, 1),
                'products_change': round(products_change, 1),
                'recent_subscriptions': recent_subscriptions,
                'top_vendors': top_vendors_data,
            }
        }, status=status.HTTP_200_OK)


# ============== GOOGLE OAUTH VIEWS ==============

class GoogleAuthView(APIView):
    """
    Handle Google OAuth authentication.
    Accepts a Google ID token or access token and returns JWT tokens.
    """
    permission_classes = [AllowAny]

    def post(self, request):
        credential = request.data.get('credential')  # ID token from Google
        access_token = request.data.get('access_token')  # Access token from Google
        user_type = request.data.get('user_type', 'buyer')  # Default to buyer

        if not credential and not access_token:
            return Response({
                'success': False,
                'message': 'Google credential or access token is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # Get Google user info
            if credential:
                # Verify ID token
                google_client_id = getattr(settings, 'GOOGLE_CLIENT_ID', None)
                if not google_client_id:
                    return Response({
                        'success': False,
                        'message': 'Google authentication not configured'
                    }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

                try:
                    idinfo = id_token.verify_oauth2_token(
                        credential,
                        google_requests.Request(),
                        google_client_id
                    )
                except ValueError as e:
                    return Response({
                        'success': False,
                        'message': f'Invalid Google token: {str(e)}'
                    }, status=status.HTTP_400_BAD_REQUEST)

                google_id = idinfo['sub']
                email = idinfo.get('email')
                full_name = idinfo.get('name', '')
                picture = idinfo.get('picture', '')
                email_verified = idinfo.get('email_verified', False)

            else:
                # Use access token to get user info
                userinfo_response = requests.get(
                    'https://www.googleapis.com/oauth2/v3/userinfo',
                    headers={'Authorization': f'Bearer {access_token}'}
                )

                if userinfo_response.status_code != 200:
                    return Response({
                        'success': False,
                        'message': 'Failed to get user info from Google'
                    }, status=status.HTTP_400_BAD_REQUEST)

                userinfo = userinfo_response.json()
                google_id = userinfo['sub']
                email = userinfo.get('email')
                full_name = userinfo.get('name', '')
                picture = userinfo.get('picture', '')
                email_verified = userinfo.get('email_verified', False)

            # Check if user exists with this Google ID
            user = User.objects.filter(google_id=google_id).first()

            if user:
                # Existing user - log them in
                if not user.is_active:
                    return Response({
                        'success': False,
                        'message': 'Account is disabled'
                    }, status=status.HTTP_403_FORBIDDEN)

                # Update profile photo if changed
                if picture and not user.profile_photo:
                    try:
                        # Download and save profile photo
                        from django.core.files.base import ContentFile
                        import urllib.request

                        img_response = urllib.request.urlopen(picture)
                        img_content = img_response.read()
                        user.profile_photo.save(
                            f'google_{google_id}.jpg',
                            ContentFile(img_content),
                            save=True
                        )
                    except Exception:
                        pass  # Ignore errors downloading profile photo

            else:
                # Check if email is already used
                if email:
                    existing_user = User.objects.filter(email=email).first()
                    if existing_user:
                        # Link Google to existing account
                        existing_user.google_id = google_id
                        existing_user.auth_provider = 'google'
                        if email_verified:
                            existing_user.is_email_verified = True
                        existing_user.save()
                        user = existing_user
                    else:
                        # Create new user
                        user = self._create_user(
                            google_id=google_id,
                            email=email,
                            full_name=full_name,
                            picture=picture,
                            user_type=user_type,
                            email_verified=email_verified
                        )
                else:
                    # No email - create new user
                    user = self._create_user(
                        google_id=google_id,
                        email=email,
                        full_name=full_name,
                        picture=picture,
                        user_type=user_type,
                        email_verified=email_verified
                    )

            # Generate tokens
            tokens = get_tokens_for_user(user)

            # Get profile based on user type
            profile_data = None
            needs_setup = False

            if user.user_type == 'vendor':
                try:
                    profile = VendorProfile.objects.get(user=user)
                    profile_data = VendorProfileSerializer(profile).data
                except VendorProfile.DoesNotExist:
                    needs_setup = True
            elif user.user_type == 'buyer':
                try:
                    profile = BuyerProfile.objects.get(user=user)
                    profile_data = BuyerProfileSerializer(profile).data
                except BuyerProfile.DoesNotExist:
                    # Create buyer profile if it doesn't exist
                    profile = BuyerProfile.objects.create(user=user)
                    profile_data = BuyerProfileSerializer(profile).data
            elif user.user_type == 'admin':
                try:
                    profile = AdminProfile.objects.get(user=user)
                    profile_data = AdminProfileSerializer(profile).data
                except AdminProfile.DoesNotExist:
                    pass

            return Response({
                'success': True,
                'message': 'Google authentication successful',
                'data': {
                    'user': UserSerializer(user).data,
                    'profile': profile_data,
                    'tokens': tokens,
                    'needs_setup': needs_setup,
                    'is_new_user': user.created_at.timestamp() > (timezone.now() - timezone.timedelta(seconds=5)).timestamp()
                }
            }, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                'success': False,
                'message': f'Authentication failed: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _create_user(self, google_id, email, full_name, picture, user_type, email_verified):
        """Create a new user from Google data"""
        import random
        import string

        # Generate a unique phone number placeholder (required field)
        # Users can update this later
        temp_phone = 'G' + ''.join(random.choices(string.digits, k=12))

        user = User.objects.create(
            google_id=google_id,
            email=email,
            full_name=full_name or 'Google User',
            phone_number=temp_phone,
            user_type=user_type,
            auth_provider='google',
            is_email_verified=email_verified,
            agreed_to_terms=True,
            is_active=True,
        )

        # Download and save profile photo
        if picture:
            try:
                from django.core.files.base import ContentFile
                import urllib.request

                img_response = urllib.request.urlopen(picture)
                img_content = img_response.read()
                user.profile_photo.save(
                    f'google_{google_id}.jpg',
                    ContentFile(img_content),
                    save=True
                )
            except Exception:
                pass

        # Create profile based on user type
        if user_type == 'buyer':
            BuyerProfile.objects.create(user=user)
        elif user_type == 'vendor':
            # Vendor profile will be created during shop setup
            pass

        return user


class GoogleLinkView(APIView):
    """Link an existing account to Google"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        credential = request.data.get('credential')
        access_token = request.data.get('access_token')

        if not credential and not access_token:
            return Response({
                'success': False,
                'message': 'Google credential is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            if credential:
                google_client_id = getattr(settings, 'GOOGLE_CLIENT_ID', None)
                if not google_client_id:
                    return Response({
                        'success': False,
                        'message': 'Google authentication not configured'
                    }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

                idinfo = id_token.verify_oauth2_token(
                    credential,
                    google_requests.Request(),
                    google_client_id
                )
                google_id = idinfo['sub']
                email = idinfo.get('email')
            else:
                userinfo_response = requests.get(
                    'https://www.googleapis.com/oauth2/v3/userinfo',
                    headers={'Authorization': f'Bearer {access_token}'}
                )
                if userinfo_response.status_code != 200:
                    return Response({
                        'success': False,
                        'message': 'Failed to verify Google token'
                    }, status=status.HTTP_400_BAD_REQUEST)
                userinfo = userinfo_response.json()
                google_id = userinfo['sub']
                email = userinfo.get('email')

            # Check if Google ID is already linked to another account
            existing = User.objects.filter(google_id=google_id).exclude(id=request.user.id).first()
            if existing:
                return Response({
                    'success': False,
                    'message': 'This Google account is already linked to another user'
                }, status=status.HTTP_400_BAD_REQUEST)

            # Link Google to current user
            request.user.google_id = google_id
            if email and not request.user.email:
                request.user.email = email
            request.user.save()

            return Response({
                'success': True,
                'message': 'Google account linked successfully'
            }, status=status.HTTP_200_OK)

        except ValueError as e:
            return Response({
                'success': False,
                'message': f'Invalid Google token: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)


class GoogleUnlinkView(APIView):
    """Unlink Google from account"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user

        if not user.google_id:
            return Response({
                'success': False,
                'message': 'No Google account linked'
            }, status=status.HTTP_400_BAD_REQUEST)

        # Make sure user has another way to log in
        if user.auth_provider == 'google' and not user.has_usable_password():
            return Response({
                'success': False,
                'message': 'Please set a password before unlinking Google'
            }, status=status.HTTP_400_BAD_REQUEST)

        user.google_id = None
        if user.auth_provider == 'google':
            user.auth_provider = 'email'
        user.save()

        return Response({
            'success': True,
            'message': 'Google account unlinked successfully'
        }, status=status.HTTP_200_OK)


# ============== VENDOR DELIVERY SETTINGS VIEWS ==============

class VendorDeliverySettingsView(APIView):
    """Get and update vendor delivery settings"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        try:
            # Check user type
            if request.user.user_type != 'vendor':
                return Response({
                    'success': False,
                    'message': 'Vendor access required'
                }, status=status.HTTP_403_FORBIDDEN)

            # Get vendor profile
            try:
                vendor = request.user.vendor_profile
            except Exception:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found. Please complete your vendor profile setup first.',
                    'error_code': 'profile_not_found'
                }, status=status.HTTP_404_NOT_FOUND)

            if not vendor:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found. Please complete your vendor profile setup first.',
                    'error_code': 'profile_not_found'
                }, status=status.HTTP_404_NOT_FOUND)

            from .models import VendorDeliveryZone

            zones = VendorDeliveryZone.objects.filter(vendor=vendor, is_active=True)
            zones_data = [{
                'id': z.id,
                'county': z.county,
                'county_display': z.get_county_display(),
                'delivery_fee': float(z.delivery_fee),
                'estimated_days': z.estimated_days,
            } for z in zones]

            return Response({
                'success': True,
                'data': {
                    'delivery_enabled': vendor.delivery_enabled,
                    'pickup_enabled': vendor.pickup_enabled,
                    'pickup_address': vendor.pickup_address,
                    'pickup_instructions': vendor.pickup_instructions,
                    'default_delivery_fee': float(vendor.default_delivery_fee),
                    'free_delivery_threshold': float(vendor.free_delivery_threshold) if vendor.free_delivery_threshold else None,
                    'delivery_zones': zones_data,
                    'vendor_county': request.user.county,
                    'vendor_town': vendor.town_area,
                }
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'success': False,
                'message': f'Server error: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def patch(self, request):
        try:
            if request.user.user_type != 'vendor':
                return Response({
                    'success': False,
                    'message': 'Vendor access required'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                vendor = request.user.vendor_profile
            except Exception:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found. Please complete your vendor profile setup first.',
                    'error_code': 'profile_not_found'
                }, status=status.HTTP_404_NOT_FOUND)

            if not vendor:
                return Response({
                    'success': False,
                    'message': 'Vendor profile not found. Please complete your vendor profile setup first.',
                    'error_code': 'profile_not_found'
                }, status=status.HTTP_404_NOT_FOUND)

            # Update delivery settings
            if 'delivery_enabled' in request.data:
                vendor.delivery_enabled = request.data['delivery_enabled']
            if 'pickup_enabled' in request.data:
                vendor.pickup_enabled = request.data['pickup_enabled']
            if 'pickup_address' in request.data:
                vendor.pickup_address = request.data['pickup_address']
            if 'pickup_instructions' in request.data:
                vendor.pickup_instructions = request.data['pickup_instructions']
            if 'default_delivery_fee' in request.data:
                vendor.default_delivery_fee = request.data['default_delivery_fee']
            if 'free_delivery_threshold' in request.data:
                threshold = request.data['free_delivery_threshold']
                vendor.free_delivery_threshold = threshold if threshold else None

            vendor.save()

            return Response({
                'success': True,
                'message': 'Delivery settings updated successfully'
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'success': False,
                'message': f'Server error: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VendorDeliveryZonesView(APIView):
    """CRUD for vendor delivery zones"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """List all delivery zones"""
        if request.user.user_type != 'vendor':
            return Response({
                'success': False,
                'message': 'Vendor access required'
            }, status=status.HTTP_403_FORBIDDEN)

        from .models import VendorDeliveryZone

        vendor = request.user.vendor_profile
        zones = VendorDeliveryZone.objects.filter(vendor=vendor)
        zones_data = [{
            'id': z.id,
            'county': z.county,
            'county_display': z.get_county_display(),
            'delivery_fee': float(z.delivery_fee),
            'estimated_days': z.estimated_days,
            'is_active': z.is_active,
        } for z in zones]

        return Response({
            'success': True,
            'data': zones_data
        }, status=status.HTTP_200_OK)

    def post(self, request):
        """Add a new delivery zone"""
        if request.user.user_type != 'vendor':
            return Response({
                'success': False,
                'message': 'Vendor access required'
            }, status=status.HTTP_403_FORBIDDEN)

        from .models import VendorDeliveryZone

        vendor = request.user.vendor_profile
        county = request.data.get('county')
        delivery_fee = request.data.get('delivery_fee')
        estimated_days = request.data.get('estimated_days', '')

        if not county or delivery_fee is None:
            return Response({
                'success': False,
                'message': 'County and delivery_fee are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        # Check if zone already exists
        existing = VendorDeliveryZone.objects.filter(vendor=vendor, county=county).first()
        if existing:
            # Update existing zone
            existing.delivery_fee = delivery_fee
            existing.estimated_days = estimated_days
            existing.is_active = True
            existing.save()
            zone = existing
        else:
            # Create new zone
            zone = VendorDeliveryZone.objects.create(
                vendor=vendor,
                county=county,
                delivery_fee=delivery_fee,
                estimated_days=estimated_days
            )

        return Response({
            'success': True,
            'message': 'Delivery zone added successfully',
            'data': {
                'id': zone.id,
                'county': zone.county,
                'county_display': zone.get_county_display(),
                'delivery_fee': float(zone.delivery_fee),
                'estimated_days': zone.estimated_days,
            }
        }, status=status.HTTP_201_CREATED)


class VendorDeliveryZoneDetailView(APIView):
    """Update or delete a specific delivery zone"""
    permission_classes = [IsAuthenticated]

    def patch(self, request, zone_id):
        """Update a delivery zone"""
        if request.user.user_type != 'vendor':
            return Response({
                'success': False,
                'message': 'Vendor access required'
            }, status=status.HTTP_403_FORBIDDEN)

        from .models import VendorDeliveryZone

        vendor = request.user.vendor_profile
        try:
            zone = VendorDeliveryZone.objects.get(id=zone_id, vendor=vendor)
        except VendorDeliveryZone.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Delivery zone not found'
            }, status=status.HTTP_404_NOT_FOUND)

        if 'delivery_fee' in request.data:
            zone.delivery_fee = request.data['delivery_fee']
        if 'estimated_days' in request.data:
            zone.estimated_days = request.data['estimated_days']
        if 'is_active' in request.data:
            zone.is_active = request.data['is_active']

        zone.save()

        return Response({
            'success': True,
            'message': 'Delivery zone updated successfully'
        }, status=status.HTTP_200_OK)

    def delete(self, request, zone_id):
        """Delete a delivery zone"""
        if request.user.user_type != 'vendor':
            return Response({
                'success': False,
                'message': 'Vendor access required'
            }, status=status.HTTP_403_FORBIDDEN)

        from .models import VendorDeliveryZone

        vendor = request.user.vendor_profile
        try:
            zone = VendorDeliveryZone.objects.get(id=zone_id, vendor=vendor)
        except VendorDeliveryZone.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Delivery zone not found'
            }, status=status.HTTP_404_NOT_FOUND)

        zone.delete()

        return Response({
            'success': True,
            'message': 'Delivery zone deleted successfully'
        }, status=status.HTTP_200_OK)


class PublicVendorDeliveryInfoView(APIView):
    """Public endpoint to get vendor's delivery options and fees for a specific county"""
    permission_classes = [AllowAny]

    def get(self, request, vendor_slug):
        customer_county = request.query_params.get('county', None)

        try:
            if vendor_slug.isdigit():
                vendor = VendorProfile.objects.get(id=int(vendor_slug))
            else:
                vendor = VendorProfile.objects.get(slug=vendor_slug)
        except VendorProfile.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Vendor not found'
            }, status=status.HTTP_404_NOT_FOUND)

        from .models import VendorDeliveryZone

        # Get delivery fee for customer's county
        delivery_fee = None
        estimated_days = None
        zone_found = False

        if customer_county and vendor.delivery_enabled:
            zone = VendorDeliveryZone.objects.filter(
                vendor=vendor,
                county=customer_county,
                is_active=True
            ).first()

            if zone:
                delivery_fee = float(zone.delivery_fee)
                estimated_days = zone.estimated_days
                zone_found = True
            else:
                # Use default fee
                delivery_fee = float(vendor.default_delivery_fee)

        # Get all available zones
        zones = VendorDeliveryZone.objects.filter(vendor=vendor, is_active=True)
        zones_data = [{
            'county': z.county,
            'county_display': z.get_county_display(),
            'delivery_fee': float(z.delivery_fee),
            'estimated_days': z.estimated_days,
        } for z in zones]

        return Response({
            'success': True,
            'data': {
                'delivery_enabled': vendor.delivery_enabled,
                'pickup_enabled': vendor.pickup_enabled,
                'pickup_address': vendor.pickup_address if vendor.pickup_enabled else None,
                'pickup_instructions': vendor.pickup_instructions if vendor.pickup_enabled else None,
                'free_delivery_threshold': float(vendor.free_delivery_threshold) if vendor.free_delivery_threshold else None,
                'default_delivery_fee': float(vendor.default_delivery_fee),
                'customer_county': customer_county,
                'delivery_fee': delivery_fee,
                'estimated_days': estimated_days,
                'zone_found': zone_found,
                'available_zones': zones_data,
            }
        }, status=status.HTTP_200_OK)


class AdminBulkEmailVendorsView(APIView):
    """Admin view to list vendors and send bulk email to them"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def get(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        vendors = VendorProfile.objects.select_related('user').filter(
            user__email__isnull=False
        ).exclude(user__email='')

        vendors_data = [{
            'id': v.user.id,
            'full_name': v.user.full_name,
            'email': v.user.email,
            'shop_name': v.shop_name or '',
            'is_upgraded': v.is_upgraded,
            'is_verified_vendor': v.is_verified_vendor,
        } for v in vendors]

        return Response({
            'success': True,
            'data': vendors_data,
        }, status=status.HTTP_200_OK)

    def post(self, request):
        import threading

        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        subject = request.data.get('subject', '').strip()
        body_html = request.data.get('body_html', '').strip()
        vendor_ids = request.data.get('vendor_ids', None)

        if not subject or not body_html:
            return Response({
                'success': False,
                'message': 'Subject and body are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        qs = VendorProfile.objects.select_related('user').filter(
            user__email__isnull=False
        ).exclude(user__email='')

        if vendor_ids:
            qs = qs.filter(user__id__in=vendor_ids)

        recipients = [{'name': v.user.full_name, 'email': v.user.email} for v in qs]

        if not recipients:
            return Response({
                'success': False,
                'message': 'No recipients found'
            }, status=status.HTTP_400_BAD_REQUEST)

        campaign = EmailCampaign.objects.create(
            subject=subject,
            body_html=body_html,
            source='vendors',
            total_recipients=len(recipients),
            created_by=request.user,
        )

        thread = threading.Thread(
            target=send_bulk_email,
            args=(subject, body_html, recipients),
            kwargs={'campaign_id': campaign.id},
            daemon=True,
        )
        thread.start()

        return Response({
            'success': True,
            'message': f'Sending emails to {len(recipients)} vendor(s) in background',
            'recipient_count': len(recipients),
            'campaign_id': campaign.id,
        }, status=status.HTTP_200_OK)


class AdminBulkEmailPreviewExcelView(APIView):
    """Admin view to preview parsed Excel contacts"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        file = request.FILES.get('file')
        if not file:
            return Response({
                'success': False,
                'message': 'No file uploaded'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not file.name.endswith(('.xlsx', '.xls')):
            return Response({
                'success': False,
                'message': 'Only .xlsx or .xls files are supported'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            import openpyxl
            wb = openpyxl.load_workbook(file, read_only=True)
            ws = wb.active

            headers = [str(cell.value or '').strip().lower() for cell in next(ws.iter_rows(min_row=1, max_row=1))]

            name_col = None
            email_col = None
            for i, h in enumerate(headers):
                if h in ('name', 'full_name', 'fullname'):
                    name_col = i
                elif h in ('email', 'email_address'):
                    email_col = i

            if email_col is None:
                wb.close()
                return Response({
                    'success': False,
                    'message': 'Excel file must have an "email" column'
                }, status=status.HTTP_400_BAD_REQUEST)

            recipients = []
            for row in ws.iter_rows(min_row=2, values_only=True):
                email = str(row[email_col] or '').strip() if email_col < len(row) else ''
                name = str(row[name_col] or '').strip() if name_col is not None and name_col < len(row) else ''
                if email and '@' in email:
                    recipients.append({'name': name, 'email': email})

            wb.close()

            return Response({
                'success': True,
                'data': recipients,
                'count': len(recipients),
            }, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                'success': False,
                'message': f'Failed to parse file: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)


class AdminBulkEmailImportView(APIView):
    """Admin view to send bulk email to imported Excel contacts"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request):
        import threading

        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        subject = request.data.get('subject', '').strip()
        body_html = request.data.get('body_html', '').strip()
        file = request.FILES.get('file')

        if not subject or not body_html:
            return Response({
                'success': False,
                'message': 'Subject and body are required'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not file:
            return Response({
                'success': False,
                'message': 'No file uploaded'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not file.name.endswith(('.xlsx', '.xls')):
            return Response({
                'success': False,
                'message': 'Only .xlsx or .xls files are supported'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            import openpyxl
            wb = openpyxl.load_workbook(file, read_only=True)
            ws = wb.active

            headers = [str(cell.value or '').strip().lower() for cell in next(ws.iter_rows(min_row=1, max_row=1))]

            name_col = None
            email_col = None
            for i, h in enumerate(headers):
                if h in ('name', 'full_name', 'fullname'):
                    name_col = i
                elif h in ('email', 'email_address'):
                    email_col = i

            if email_col is None:
                wb.close()
                return Response({
                    'success': False,
                    'message': 'Excel file must have an "email" column'
                }, status=status.HTTP_400_BAD_REQUEST)

            recipients = []
            for row in ws.iter_rows(min_row=2, values_only=True):
                email = str(row[email_col] or '').strip() if email_col < len(row) else ''
                name = str(row[name_col] or '').strip() if name_col is not None and name_col < len(row) else ''
                if email and '@' in email:
                    recipients.append({'name': name, 'email': email})

            wb.close()

            if not recipients:
                return Response({
                    'success': False,
                    'message': 'No valid email addresses found in file'
                }, status=status.HTTP_400_BAD_REQUEST)

            campaign = EmailCampaign.objects.create(
                subject=subject,
                body_html=body_html,
                source='import',
                total_recipients=len(recipients),
                created_by=request.user,
            )

            thread = threading.Thread(
                target=send_bulk_email,
                args=(subject, body_html, recipients),
                kwargs={'campaign_id': campaign.id},
                daemon=True,
            )
            thread.start()

            return Response({
                'success': True,
                'message': f'Sending emails to {len(recipients)} contact(s) in background',
                'recipient_count': len(recipients),
                'campaign_id': campaign.id,
            }, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                'success': False,
                'message': f'Failed to process file: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)


class AdminBulkEmailCampaignsView(APIView):
    """Admin view to list all email campaigns"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        campaigns = EmailCampaign.objects.all()[:50]
        data = [{
            'id': c.id,
            'subject': c.subject,
            'source': c.source,
            'status': c.status,
            'total_recipients': c.total_recipients,
            'sent_count': c.sent_count,
            'failed_count': c.failed_count,
            'created_at': c.created_at.isoformat(),
            'completed_at': c.completed_at.isoformat() if c.completed_at else None,
        } for c in campaigns]

        return Response({
            'success': True,
            'data': data,
        }, status=status.HTTP_200_OK)


class AdminBulkEmailCampaignDetailView(APIView):
    """Admin view to get single campaign detail"""
    permission_classes = [IsAuthenticated]

    def get(self, request, campaign_id):
        if request.user.user_type != 'admin':
            return Response({
                'success': False,
                'message': 'Admin access required'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            c = EmailCampaign.objects.get(pk=campaign_id)
        except EmailCampaign.DoesNotExist:
            return Response({
                'success': False,
                'message': 'Campaign not found'
            }, status=status.HTTP_404_NOT_FOUND)

        return Response({
            'success': True,
            'data': {
                'id': c.id,
                'subject': c.subject,
                'source': c.source,
                'status': c.status,
                'total_recipients': c.total_recipients,
                'sent_count': c.sent_count,
                'failed_count': c.failed_count,
                'failed_emails': [e.strip() for e in c.failed_emails.split(',') if e.strip()] if c.failed_emails else [],
                'error_message': c.error_message,
                'created_at': c.created_at.isoformat(),
                'completed_at': c.completed_at.isoformat() if c.completed_at else None,
            },
        }, status=status.HTTP_200_OK)
