import base64
import os
import datetime
from django.core.files.base import ContentFile
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from accounts.models import Customers, CustomerDocument
from customer_api.serializers.CustomerSerializer import CustomerSerializer

import json


@api_view(['POST'])
def update_customer(request, customer_id):

    try:
        customer = Customers.objects.get(pk=customer_id)
    except Customers.DoesNotExist:
        return Response({"error": "Customer not found"}, status=status.HTTP_404_NOT_FOUND)

    # update_data = request.POST.get("data")
    # profile_image = request.FILES.get("profile_image")
    # update_data = request.POST.get("data")  # Extract JSON string from form-data
    # update_data = json.loads(update_data)
    update_data = json.loads(request.body.decode('utf-8'))

    try:
        profile_image = update_data.get("profile_image")  # Uint8List (bytes) or base64
        if profile_image and not profile_image.startswith(('https://', 'http://')):
            # print("profile_image", profile_image)
            try:
                update_data["profile_image"] = profile_image
                if isinstance(profile_image, str):  # If Flutter sends it as base64
                    format, imgstr = profile_image.split(';base64,') if ';base64,' in profile_image else ("", profile_image)
                    profile_image_bytes = base64.b64decode(imgstr)

                elif isinstance(profile_image, list):  # If Flutter sends raw Uint8List (as a list of integers)
                    profile_image_bytes = bytes(profile_image)

                file_name = f"customer_{customer_id}.jpg"
                update_data["profile_image"] = ContentFile(profile_image_bytes, name=file_name)
            except Exception as e:
                update_data.pop("profile_image", None)
        else:
            update_data.pop("profile_image", None)
    except Exception as e:
        update_data.pop("profile_image", None)

    # print(update_data,1)
    if not update_data:
        return Response({'error': 'Empty request body'}, status=400)
    # print(customer.qr_code, update_data.get("qr_code"))
    if customer.qr_code==update_data.get("qr_code"):

        serializer = CustomerSerializer(instance=customer, data=update_data, partial=True)

        if serializer.is_valid():
            serializer.save()

            # ===================================================================================
            # Handle Document Uploads
            documents = update_data.get("documents", [])  # List of base64/uint8 documents
            filenames = update_data.get("filenames", [])  # Corresponding filenames

            # Validate document structure
            if not isinstance(documents, list) or not isinstance(filenames, list):
                return Response({"error": "Invalid document format"}, status=status.HTTP_400_BAD_REQUEST)

            if len(documents) != len(filenames):
                return Response({"error": "Mismatch between documents and filenames"},
                                status=status.HTTP_400_BAD_REQUEST)

            uploaded_documents = []

            # Allowed file types
            allowed_extensions = [".pdf", ".jpg", ".jpeg", ".png", ".docx"]

            for i, document in enumerate(documents):
                original_filename = os.path.basename(filenames[i])  # Ensure filename safety
                filename, file_extension = os.path.splitext(original_filename)  # Get extension

                # Validate file type
                if file_extension.lower() not in allowed_extensions:
                    return Response({"error": f"File type {file_extension} is not allowed."},
                                    status=status.HTTP_400_BAD_REQUEST)

                # Prevent duplicate filenames by adding timestamp
                timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                safe_filename = f"{filename}_{timestamp}{file_extension}"

                # Convert document (Base64 or Uint8List)
                if isinstance(document, str):  # If base64 string
                    try:
                        format, imgstr = document.split(';base64,') if ';base64,' in document else ("", document)
                        document_bytes = base64.b64decode(imgstr)
                    except Exception as e:
                        return Response({"error": f"Invalid base64 encoding for {original_filename}: {str(e)}"},
                                        status=status.HTTP_400_BAD_REQUEST)

                elif isinstance(document, list):  # If Uint8List (list of integers)
                    document_bytes = bytes(document)

                else:
                    return Response({"error": f"Unsupported file format for {original_filename}"},
                                    status=status.HTTP_400_BAD_REQUEST)

                # Save document in the model
                doc_instance = CustomerDocument.objects.create(
                    customer=customer,
                    doc_name=original_filename,
                    document=ContentFile(document_bytes, name=safe_filename)
                )

                uploaded_documents.append({
                    "id": doc_instance.id,
                    "doc_name": doc_instance.doc_name,
                    "document_url": doc_instance.document.url
                })

            # Attach uploaded documents to the response
            response_data = serializer.data
            response_data["documents"] = uploaded_documents

            return Response(response_data, status=status.HTTP_200_OK)

            # ===================================================================================

    else:
        return Response({"error": "Customer data invalid"}, status=status.HTTP_400_BAD_REQUEST)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)