from django.contrib import admin
from django.template.response import TemplateResponse
from .models import Account
import uuid

@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):
    list_display = ('uuid', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('uuid',)
    actions = ['generate_sample_accounts', 'view_raw_tigerbeetle_data'] # Renamed action

    def generate_sample_accounts(self, request, queryset):
        import tigerbeetle as tb
        from .tigerbeetle_client import tigerbeetle_client

        generated_count = 0
        errors = []
        for _ in range(5):
            new_account_uuid = uuid.uuid4()
            try:
                local_account = Account.objects.create(uuid=new_account_uuid)

                tb_account = tb.Account(
                    id=new_account_uuid.int,
                    ledger=700,
                    code=10,
                    flags=tb.AccountFlags.NONE
                )

                creation_results = tigerbeetle_client.create_accounts([tb_account])
                if creation_results:
                    for error_obj in creation_results:
                        if hasattr(error_obj, 'error') and error_obj.error != tb.AccountError.OK:
                            errors.append(f"Account ID: {new_account_uuid}, Error: {error_obj.error.name}")
                        else:
                            errors.append(f"Account ID: {new_account_uuid}, Unknown error: {str(error_obj)}")
                    local_account.delete()
                else:
                    generated_count += 1
            except Exception as e:
                errors.append(f"Failed to create account {new_account_uuid}: {e}")

        if errors:
            self.message_user(request, f"Generated {generated_count} accounts. Some errors occurred: {', '.join(errors)}", level='ERROR')
        else:
            self.message_user(request, f"Successfully generated {generated_count} sample accounts.")

    generate_sample_accounts.short_description = "Generate 5 sample accounts"

    def view_raw_tigerbeetle_data(self, request, queryset):
        import tigerbeetle as tb
        from .tigerbeetle_client import tigerbeetle_client

        LEDGER = 700
        CODE = 10

        source_account_id = uuid.uuid4()
        destination_account_id = uuid.uuid4()
        bank_account_id = uuid.uuid4()

        local_accounts_to_delete = []
        local_accounts_to_delete.append(Account.objects.create(uuid=source_account_id))
        local_accounts_to_delete.append(Account.objects.create(uuid=destination_account_id))
        local_accounts_to_delete.append(Account.objects.create(uuid=bank_account_id))

        accounts_to_create = [
            tb.Account(id=source_account_id.int, ledger=LEDGER, code=CODE, flags=tb.AccountFlags.NONE),
            tb.Account(id=destination_account_id.int, ledger=LEDGER, code=CODE, flags=tb.AccountFlags.NONE),
            tb.Account(id=bank_account_id.int, ledger=LEDGER, code=CODE, flags=tb.AccountFlags.NONE),
        ]

        account_creation_errors = tigerbeetle_client.create_accounts(accounts_to_create)
        if account_creation_errors:
            error_msg = f"Failed to create accounts in TigerBeetle. Raw results: {account_creation_errors}"
            self.message_user(request, error_msg, level='ERROR')
            for acc in local_accounts_to_delete:
                acc.delete()
            return TemplateResponse(request, 'admin/billing_app/account/display_balances.html', {'title': "Error", 'error_message': error_msg})

        all_transfer_ids = []

        initial_fund_transfer = tb.Transfer(
            id=uuid.uuid4().int,
            debit_account_id=bank_account_id.int,
            credit_account_id=source_account_id.int,
            amount=1000,
            ledger=LEDGER,
            code=CODE,
        )
        fund_results = tigerbeetle_client.create_transfers([initial_fund_transfer])
        if fund_results:
            error_msg = f"Failed to fund source account. Raw results: {fund_results}"
            self.message_user(request, error_msg, level='ERROR')
            return TemplateResponse(request, 'admin/billing_app/account/display_balances.html', {'title': "Error", 'error_message': error_msg})
        all_transfer_ids.append(initial_fund_transfer.id)

        transfers_performed_count = 0
        for i in range(1, 6):
            transfer = tb.Transfer(
                id=uuid.uuid4().int,
                debit_account_id=source_account_id.int,
                credit_account_id=destination_account_id.int,
                amount=100,
                ledger=LEDGER,
                code=CODE,
            )
            transfer_results = tigerbeetle_client.create_transfers([transfer])
            if transfer_results:
                self.message_user(request, f"Transaction {i} failed. Raw results: {transfer_results}", level='ERROR')
            else:
                all_transfer_ids.append(transfer.id)
                transfers_performed_count += 1

        self.message_user(request, f"Successfully performed {transfers_performed_count} transfers.")

        account_ids_to_lookup = [source_account_id.int, destination_account_id.int, bank_account_id.int]
        detailed_accounts = tigerbeetle_client.lookup_accounts(account_ids_to_lookup)

        context = {
            'title': "Raw TigerBeetle Data",
            'accounts': [],
            'transfers': [],
            'site_header': self.admin_site.site_header,
            'site_title': self.admin_site.site_title,
            'site_url': self.admin_site.site_url,
            'has_permission': True,
            'is_popup': False,
            'is_nav_sidebar_enabled': True,
        }

        for account in detailed_accounts:
            if isinstance(account, tb.Account):
                account_uuid = uuid.UUID(int=account.id)
                net_balance = account.credits_posted - account.debits_posted
                context['accounts'].append({
                    'uuid': account_uuid,
                    'debits_posted': account.debits_posted,
                    'credits_posted': account.credits_posted,
                    'net_balance': net_balance,
                    'flags': str(account.flags),
                    'ledger': account.ledger,
                    'code': account.code,
                    'timestamp': account.timestamp,
                })
            else:
                context['accounts'].append({
                    'uuid': getattr(account, 'id', 'Unknown'),
                    'error': "Could not retrieve balance details."
                })

        return TemplateResponse(request, 'admin/billing_app/account/display_balances.html', context)

    view_raw_tigerbeetle_data.short_description = "View raw TigerBeetle data"

