from django.shortcuts import render
from rest_framework import viewsets
from .serializers import FixedAssetSerializer, DepreciationHistorySerializers, DepreciationRateSerializers, FixedAssetCategorySerializers
from questbanker_api.utils import get_current_user
from .models import DepreciationRate, FixedAsset
from ledgers.models import SystemTransactions
from ledgers.ledgers_helper import *
from organisations.models import OrganisationBranch
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from .helper import *
from rest_framework.views import APIView
from ledgers.serializers import *



class FixedAssetView(viewsets.ModelViewSet):
    serializer_class = FixedAssetSerializer 

    def perform_create(self, serializer):
        organisation_id = get_current_user(self.request, 'organisation_id', None)
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        depreciation_rate_id = self.request.data.get('depRate')
        depreciation_rate = DepreciationRate.objects.get(id=depreciation_rate_id)
        debit_chart_id=self.request.data.get('debit_acct')
        credit_chart_id=self.request.data.get('credit_acct')
        debit_chart = OrganisationSubAccount.objects.get(pk=debit_chart_id)
        credit_chart = OrganisationSubAccount.objects.get(pk=credit_chart_id)
        depDRAcct = OrganisationSubAccount.objects.get(pk=self.request.data.get('depDebit'))
        depCRAcct = OrganisationSubAccount.objects.get(pk=self.request.data.get('depCredit'))
        reference_no = generate_reference_no(debit_chart.account_line, organisation_id, 'ast')
        debitCredit = SystemTransactions(amount=self.request.data.get('amount'), heading=self.request.data.get('name'), record_date=self.request.data.get('date'),payment_method=self.request.data.get('paymentMethod'), voucher_no=self.request.data.get('voucher'), reference_no=reference_no,debit_chart_id=debit_chart_id,credit_chart_id=credit_chart_id, branch_id=branch_id,added_by=self.request.user)
        debitCredit.save()
        serializer.save(name=self.request.data.get('name'), description=self.request.data.get('description'), amount=self.request.data.get('amount'), payment_method=self.request.data.get('paymentMethod'), depreciation_method=self.request.data.get('depMethod'), added_by=self.request.user, depreciation_rate=depreciation_rate, debit_id=debit_chart_id, credit_id= credit_chart_id, reference_no=reference_no, cheque_no=self.request.data.get('cheque'), voucher_no=self.request.data.get('voucher'), branch_id=branch_id, deprecation_dr_acct= depDRAcct, deprecation_cr_acct=depCRAcct, frequency=self.request.data.get('depAcctFreq'), depreciation_type=self.request.data.get('depAcctMethod'))

class FixedAssetsListView(viewsets.ModelViewSet):
    serializer_class = FixedAssetSerializer

    def get_queryset(self):
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        fixed_assets = FixedAsset.objects.select_related('depreciation_rate').filter(deleted=False, branch_id=branch_id)
        return fixed_assets

class FixedAssetConfigView(viewsets.ModelViewSet):
    serializer_class = DepreciationRateSerializers

    def perform_create(self, serializer):
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        serializer.save(description=self.request.data.get('description'), rate=self.request.data.get('rate'), frequency=self.request.data.get('frequency'), branch_id=branch_id, added_by=self.request.user)

class FixedAssetConfigListView(viewsets.ModelViewSet):
    serializer_class = DepreciationRateSerializers

    def get_queryset(self):
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        return DepreciationRate.objects.filter(deleted=False, branch_id=branch_id)
    
class FixedAssetDepreciation(viewsets.ModelViewSet):
    serializer_class = FixedAssetSerializer
    # @action(detail=True, methods=['put', 'patch'])
    def update(self, request, pk=None):
        # fixed_assets = FixedAsset.objects.select_related('depreciation_rate').filter(deleted=False, pk=id).first()
        fixed_asset = FixedAsset.objects.select_related('depreciation_rate').filter(deleted=False, pk=pk).first()
        # return fixed_asset
            # Check if the asset exists
        if not fixed_asset:
            return Response({"detail": "Fixed asset not found."}, status=status.HTTP_404_NOT_FOUND)
        
        # Update the asset fields here if needed
        serializer = self.get_serializer(fixed_asset, data=request.data, partial=True)  # Use partial=True if not all fields are being updated
        if serializer.is_valid():
            serializer.save()

            transaction = SystemTransactions.objects.get(reference_no=request.data['reference_no'])
            transaction.amount = request.data['amount']
            transaction.deleted = request.data['deleted']
            transaction.save()

            return Response(serializer.data)  # Return the updated data
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  # Return errors if validation fails



class ManualDepreciation(viewsets.ModelViewSet):
    serializer_class = FixedAssetSerializer

    def update(self, request, pk=None):
        organisation_id = get_current_user(self.request, 'organisation_id', None)
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        user_id = self.request.user
        # fixed_assets = FixedAsset.objects.select_related('depreciation_rate').filter(deleted=False, pk=id).first()
        fixed_asset = FixedAsset.objects.select_related('depreciation_rate').filter(deleted=False, pk=pk).first()
        # return fixed_asset
            # Check if the asset exists
        if not fixed_asset:
            return Response({"detail": "Fixed asset not found."}, status=status.HTTP_404_NOT_FOUND)
        
        manually = depreciation(fixed_asset.id, organisation_id, user_id, branch_id)
        if not manually:
            return Response({"detail": "Fixed asset depreciation failed.", "error":manually}, status=status.HTTP_412_PRECONDITION_FAILED)

        # Serialize the updated asset data
        serializer = self.get_serializer(fixed_asset)
        return Response(serializer.data, status=status.HTTP_200_OK)

class LedgerAccountByAccountCode(viewsets.ViewSet):

    def list(self, request, format=None):
        code = request.GET.get('code', None)
        organisation_id = get_current_user(request, 'organisation_id')
        accounts = get_chart_of_account_by_code(code, organisation_id)
        accounts = [accounts]
        
        # Serialize the accounts
        serializer = OrganisationSubAccountSerializer(accounts, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    


# class EditDepreciationRates(viewsets.ModelViewSet):


class FixedAssetReport(viewsets.ModelViewSet):
    

    def list(self, request):
        branch_id = get_current_user(self.request, 'organisation_branch_id', None)
        start_date = request.GET.get('start_date', None)
        end_date = request.GET.get('end_date', None)
        response = get_fixed_asset_report(start_date, end_date, branch_id)
        return Response({"response": "Fixed asset report", "data": response}, status=status.HTTP_200_OK)
        



