from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import MultiPartParser, FormParser
from django.shortcuts import get_object_or_404
from rest_framework import status

from apps.reviews.models import BusinessPlatformLinks
from apps.reviews.serializers import BusinessPlatformLinksSerializer

from .models import APIKey, App, ReviewPageBranding
from .serializers import ReviewPageBrandingSerializer

import logging

logger = logging.getLogger(__name__)


class ReviewPageBrandingView(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]  

    def get(self, request, app_id):
        app = get_object_or_404(App, id=app_id, company=request.user.company)
        branding = getattr(app, "branding", None)
        serializer = ReviewPageBrandingSerializer(branding)
        return Response(serializer.data if branding else {})

    def post(self, request, app_id):
        app = get_object_or_404(App, id=app_id, company=request.user.company)
        branding, _ = ReviewPageBranding.objects.get_or_create(app=app)
        serializer = ReviewPageBrandingSerializer(
            instance=branding,
            data=request.data,
            partial=True
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "detail": "Branding updated successfully",
            "branding": serializer.data
        })

class BusinessPlatformLinksView(APIView):
    """
    Admin endpoint for managing platform links (requires API key)
    GET: Retrieve platform links for the authenticated app
    POST: Create platform links for the authenticated app  
    PUT: Update platform links for the authenticated app
    DELETE: Delete platform links for the authenticated app
    """
    
    def get_app_from_api_key(self, request):
        """Helper method to get app from API key"""
        api_key_value = request.headers.get("X-API-KEY")
        if not api_key_value:
            return None, Response({"detail": "API key required"}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            api_key = APIKey.objects.get(key=api_key_value, revoked=False)
            return api_key.app, None
        except APIKey.DoesNotExist:
            return None, Response({"detail": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)

    def get(self, request, *args, **kwargs):
        """Get platform configuration for the authenticated app"""
        app, error_response = self.get_app_from_api_key(request)
        if error_response:
            return error_response

        try:
            platform_links = BusinessPlatformLinks.objects.get(app=app)
            serializer = BusinessPlatformLinksSerializer(platform_links)
            return Response(serializer.data)
        except BusinessPlatformLinks.DoesNotExist:
            return Response({
                "message": "No platform configuration found for this app",
                "app_name": app.name,
                "configured": False
            }, status=status.HTTP_404_NOT_FOUND)

    def post(self, request, *args, **kwargs):
        """Create platform configuration for the authenticated app"""
        app, error_response = self.get_app_from_api_key(request)
        if error_response:
            return error_response

        # Check if configuration already exists
        if BusinessPlatformLinks.objects.filter(app=app).exists():
            return Response({
                "detail": "Platform configuration already exists for this app. Use PUT to update."
            }, status=status.HTTP_400_BAD_REQUEST)

        serializer = BusinessPlatformLinksSerializer(data=request.data)
        if serializer.is_valid():
            platform_links = serializer.save(app=app)
            
            # Log the creation
            logger.info(f"Platform links created for app {app.name} ({app.id})")
            
            return Response(BusinessPlatformLinksSerializer(platform_links).data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, *args, **kwargs):
        """Update platform configuration for the authenticated app"""
        app, error_response = self.get_app_from_api_key(request)
        if error_response:
            return error_response

        try:
            platform_links = BusinessPlatformLinks.objects.get(app=app)
        except BusinessPlatformLinks.DoesNotExist:
            return Response({
                "detail": "No platform configuration found for this app. Use POST to create."
            }, status=status.HTTP_404_NOT_FOUND)

        serializer = BusinessPlatformLinksSerializer(
            platform_links, 
            data=request.data, 
            partial=True
        )
        
        if serializer.is_valid():
            platform_links = serializer.save()
            
            # Log the update
            logger.info(f"Platform links updated for app {app.name} ({app.id})")
            
            return Response(BusinessPlatformLinksSerializer(platform_links).data)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, *args, **kwargs):
        """Delete platform configuration for the authenticated app"""
        app, error_response = self.get_app_from_api_key(request)
        if error_response:
            return error_response

        try:
            platform_links = BusinessPlatformLinks.objects.get(app=app)
            platform_links.delete()
            
            # Log the deletion
            logger.info(f"Platform links deleted for app {app.name} ({app.id})")
            
            return Response({
                "message": "Platform configuration deleted successfully"
            }, status=status.HTTP_204_NO_CONTENT)
        except BusinessPlatformLinks.DoesNotExist:
            return Response({
                "detail": "No platform configuration found for this app"
            }, status=status.HTTP_404_NOT_FOUND)


class BusinessPlatformLinksStatusView(APIView):
    """Get a quick status of platform configuration for dashboard (requires API key)"""
    
    def get(self, request, *args, **kwargs):
        api_key_value = request.headers.get("X-API-KEY")
        if not api_key_value:
            return Response({"detail": "API key required"}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            api_key = APIKey.objects.get(key=api_key_value, revoked=False)
            app = api_key.app
        except APIKey.DoesNotExist:
            return Response({"detail": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            platform_links = BusinessPlatformLinks.objects.get(app=app)
            
            # Count configured platforms
            platforms_configured = 0
            platform_status = {}
            
            if platform_links.google_review_url:
                platforms_configured += 1
                platform_status['google'] = True
            else:
                platform_status['google'] = False
                
            if platform_links.tripadvisor_review_url:
                platforms_configured += 1
                platform_status['tripadvisor'] = True
            else:
                platform_status['tripadvisor'] = False
                
            if platform_links.facebook_review_url:
                platforms_configured += 1
                platform_status['facebook'] = True
            else:
                platform_status['facebook'] = False
                
            if platform_links.booking_review_url:
                platforms_configured += 1
                platform_status['booking'] = True
            else:
                platform_status['booking'] = False

            return Response({
                "configured": True,
                "platforms_configured": platforms_configured,
                "total_platforms": 4,
                "platform_status": platform_status,
                "business_name": platform_links.business_name or app.name,
                "last_updated": platform_links.updated_at.isoformat()
            })
            
        except BusinessPlatformLinks.DoesNotExist:
            return Response({
                "configured": False,
                "platforms_configured": 0,
                "total_platforms": 4,
                "platform_status": {
                    'google': False,
                    'tripadvisor': False, 
                    'facebook': False,
                    'booking': False
                },
                "business_name": app.name,
                "message": "No platform configuration found"
            })