from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.hashers import make_password, check_password
from admin_panel.models import *
from django.contrib.auth import authenticate  # ✅ Import the correct one

from user_panel.models import *
from .authentication import authenticated
from admin_panel.functions import *
from user_panel.models import EndUser


class AdminLogIn(APIView):
    def post(self, request):
        try:
            email = request.data.get("email")
            password = request.data.get("password")

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

            user = authenticate(username=email, password=password)
            
            if user:
                refresh = RefreshToken.for_user(user)

                return Response({
                    "message": "Login successful",
                    "access": str(refresh.access_token),
                    "refresh": str(refresh),
                    "user_id": user.id,
                    "email": user.email,
                    "is_staff": user.is_staff
                }, status=status.HTTP_200_OK)
            else:
                return Response({"message": "Invalid email or password"}, status=status.HTTP_401_UNAUTHORIZED)

        except Exception as e:
            return Response({"message": f"Login failed: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class AdminRegister(APIView):
    def post(self, request):
        try:
            email = request.data.get("email")
            password = request.data.get("password")

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

            if User.objects.filter(email=email).exists():
                return Response({"message": "User with this email already exists"}, status=status.HTTP_400_BAD_REQUEST)

            user = User.objects.create_user(
                username=email,  
                email=email,
                password=password
            )

            super_admin = SuperAdmin.objects.create(
                user=user,
                email=email,
                password=make_password(password)  
            )

            refresh = RefreshToken.for_user(user)

            return Response({
                "message": "Admin registered successfully",
                "access": str(refresh.access_token),
                "refresh": str(refresh),
                "user_id": user.id,
                "email": user.email
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({"message": f"Registration failed: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class AdminProfile(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
            user_obj = User.objects.filter(id=uid).first()


            if not user_obj:
                
                return Response({'message': 'user not found'}, status=status.HTTP_404_NOT_FOUND)

            admin_obj  = SuperAdmin.objects.all().first()
            if not admin_obj:
                return Response({"message":'Your account has been Inactive, Please contact to admin.',"email":admin_obj.email},status=status.HTTP_406_NOT_ACCEPTABLE)
            
            all_data ={

                "firstName":admin_obj.firstName,
                "gender":admin_obj.gender,
                "phoneNumber":admin_obj.phoneNumber,
                "image":admin_obj.image
            }
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched Successfully','all_data':all_data})
        except Exception as e:
            return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        



    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            user_obj = User.objects.filter(id = uid).first()

            if not user_obj:
                return Response({'message': 'user not found'}, status=status.HTTP_404_NOT_FOUND)
            
            admin_obj = SuperAdmin.objects.filter(user=user_obj).first()
            if not admin_obj:
                return Response({'message': 'Admin not found'}, status=status.HTTP_404_NOT_FOUND)
            
            firstName = request.data.get("firstName")
            gender = request.data.get("gender")
            phoneNumber =request.data.get("phoneNumber")
            image = request.data.get("image")

            admin_obj.firstName = firstName
            admin_obj.gender = gender
            admin_obj.phoneNumber = phoneNumber
            admin_obj.image = image
            admin_obj.save()
            print("user_obj",admin_obj)

            return Response({'status_code':status.HTTP_200_OK,'status_message':'Profile updated successfully'})
        except Exception as e:
            return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class AdminUploadImages(APIView):
    def post(self,request):
        try:
            data = request.data
            images = data.getlist('image')
            image_urls = []
            for image in images:
                image_path = uploadTheDocument(image)
                image_urls.append(image_path)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':image_urls})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class AdminChatBotListing(APIView):

    def get(self, request):
        try:
            try:
                uid = authenticated(request)
                print("---",uid)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)

            user_obj = EndUser.objects.filter(enduser_id=uid).first()
            print("=======1===",user_obj)
            if not user_obj:
                return Response({'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND)

            if user_obj.is_admin:
                chatBots = chatBot_setting.objects.all()
            else:
                chatBots = chatBot_setting.objects.filter(user=user_obj)  

            chatbot_listing = []
            for bot in chatBots:
                chatbot_listing.append({
                    "id": bot.id,
                    "chatbot_name": bot.chatbot_name,
                    "categories_name": bot.categories_name,
                    "description": bot.description,
                    "pdf_data": bot.pdf_data,
                    "created_at": bot.created_at.isoformat()
                })

            return Response({'message': 'Success', 'data': chatbot_listing}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'message': 'Internal server error', 'details': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
