<x-layouts.admin title="Brokerage Management" activePage="admin-brokerage">
<h2 class="text-2xl font-serif tracking-tight mb-6">Brokerage Management</h2>

{{-- Portfolio Summary --}}
@php
    $totalBalance = $accounts->sum('balance');
    $totalPLAll = $accounts->sum(fn($a) => $a->holdings->sum('profit_loss'));
    $totalHoldings = $accounts->sum(fn($a) => $a->holdings->count());
@endphp
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
    <div class="bg-surface-container rounded-lg p-5">
        <p class="text-xs font-semibold uppercase text-on-surface-variant">Total AUM</p>
        <p class="text-2xl font-bold text-on-surface mt-1">${{ number_format($totalBalance, 2) }}</p>
    </div>
    <div class="bg-surface-container rounded-lg p-5">
        <p class="text-xs font-semibold uppercase text-on-surface-variant">Total P/L</p>
        <p class="text-2xl font-bold mt-1 {{ $totalPLAll >= 0 ? 'text-green-600' : 'text-red-600' }}">{{ $totalPLAll >= 0 ? '+' : '' }}${{ number_format($totalPLAll, 2) }}</p>
    </div>
    <div class="bg-surface-container rounded-lg p-5">
        <p class="text-xs font-semibold uppercase text-on-surface-variant">Total Holdings</p>
        <p class="text-2xl font-bold text-on-surface mt-1">{{ $totalHoldings }}</p>
    </div>
</div>

{{-- Requests Table --}}
<h3 class="text-lg font-semibold text-on-surface mb-3">Account Requests</h3>
<div class="bg-surface-container rounded-lg overflow-x-auto">
    <table class="w-full text-left text-sm min-w-[800px]">
        <thead class="text-xs uppercase text-on-surface-variant border-b border-outline-variant/20">
            <tr>
                <th class="px-6 py-4">User</th>
                <th class="px-6 py-4">Account Type</th>
                <th class="px-6 py-4">Status</th>
                <th class="px-6 py-4">Date</th>
                <th class="px-6 py-4 text-right">Balance</th>
                <th class="px-6 py-4 text-right">Profit / Loss</th>
                <th class="px-6 py-4">Actions</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-outline-variant/10">
            @forelse($requests as $req)
            @php
                $isApproved = $req->status === \App\Enums\RequestStatus::Approved;
                $hasAccount = $isApproved && $req->account;
                $totalPL = $hasAccount ? $req->account->holdings->sum(fn($h) => ($h->current_price - $h->purchase_price) * $h->quantity) : null;
            @endphp
            <tr>
                <td class="px-6 py-4 font-medium">{{ $req->user->first_name }} {{ $req->user->last_name }}</td>
                <td class="px-6 py-4">{{ $req->brokerage_type->label() }}</td>
                <td class="px-6 py-4">
                    <span class="text-xs px-2 py-0.5 rounded {{ $req->status === \App\Enums\RequestStatus::Pending ? 'bg-yellow-100 text-yellow-700' : ($req->status === \App\Enums\RequestStatus::Approved ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700') }}">
                        {{ ucfirst($req->status->value) }}
                    </span>
                </td>
                <td class="px-6 py-4 text-on-surface-variant">{{ $req->created_at->format('M d, Y') }}</td>
                <td class="px-6 py-4 text-right font-semibold">
                    @if($hasAccount)
                        ${{ number_format($req->account->balance, 2) }}
                    @else
                        <span class="text-on-surface-variant">—</span>
                    @endif
                </td>
                <td class="px-6 py-4 text-right font-semibold">
                    @if($hasAccount)
                        <span class="{{ $totalPL >= 0 ? 'text-green-600' : 'text-red-600' }}">
                            {{ $totalPL >= 0 ? '+' : '' }}${{ number_format($totalPL, 2) }}
                        </span>
                    @else
                        <span class="text-on-surface-variant">—</span>
                    @endif
                </td>
                <td class="px-6 py-4">
                    @if($req->status === \App\Enums\RequestStatus::Pending)
                    <div class="flex gap-2">
                        <form method="POST" action="{{ route('admin.brokerage.requests.approve', $req) }}">
                            @csrf
                            <button class="text-xs bg-green-600 text-white px-3 py-1 rounded hover:bg-green-700">Approve</button>
                        </form>
                        <form method="POST" action="{{ route('admin.brokerage.requests.reject', $req) }}" class="flex gap-1">
                            @csrf
                            <input type="text" name="admin_note" placeholder="Reason" class="text-xs border rounded px-2 py-1 w-32">
                            <button class="text-xs bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700">Reject</button>
                        </form>
                    </div>
                    @elseif($isApproved)
                        <div class="flex gap-2">
                            <a href="{{ route('admin.users.accounts', $req->user) }}" class="text-xs bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">View Account</a>
                            @if($hasAccount)
                                <a href="{{ route('admin.brokerage.holdings', $req->account) }}" class="text-xs bg-primary text-white px-3 py-1 rounded hover:opacity-90">Edit & Manage P/L</a>
                            @endif
                        </div>
                    @elseif($req->status === \App\Enums\RequestStatus::Rejected)
                        <span class="text-xs text-on-surface-variant">{{ $req->admin_note ?? '—' }}</span>
                    @else
                        <span class="text-on-surface-variant">—</span>
                    @endif
                </td>
            </tr>
            @empty
            <tr><td colspan="7" class="px-6 py-8 text-center text-on-surface-variant">No brokerage requests found.</td></tr>
            @endforelse
        </tbody>
    </table>
</div>
<div class="mt-4">{{ $requests->links() }}</div>

{{-- P/L Charts --}}
@if($accounts->flatMap->holdings->count())
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-8">
    <div class="bg-surface-container rounded-lg p-6">
        <h3 class="font-semibold text-on-surface mb-4">P/L by Account</h3>
        <div style="height: 300px;"><canvas id="accountPlChart"></canvas></div>
    </div>
    <div class="bg-surface-container rounded-lg p-6">
        <h3 class="font-semibold text-on-surface mb-4">Balance Distribution</h3>
        <div style="height: 300px;"><canvas id="balanceChart"></canvas></div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script>
const acctLabels = {!! json_encode($accounts->map(fn($a) => $a->user->first_name . ' ' . strtoupper($a->account_type->value))->values()) !!};

new Chart(document.getElementById('accountPlChart'), {
    type: 'bar',
    data: {
        labels: acctLabels,
        datasets: [{
            label: 'Profit/Loss ($)',
            data: {!! json_encode($accounts->map(fn($a) => (float) $a->holdings->sum('profit_loss'))->values()) !!},
            backgroundColor: {!! json_encode($accounts->map(fn($a) => $a->holdings->sum('profit_loss') >= 0 ? 'rgba(5,150,105,0.7)' : 'rgba(220,38,38,0.7)')->values()) !!},
            borderRadius: 6
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, ticks: { callback: v => '$' + v.toLocaleString() } } }
    }
});

new Chart(document.getElementById('balanceChart'), {
    type: 'doughnut',
    data: {
        labels: acctLabels,
        datasets: [{
            data: {!! json_encode($accounts->map(fn($a) => (float) $a->balance)->values()) !!},
            backgroundColor: ['#1d4ed8','#059669','#d97706','#7c3aed','#dc2626','#0891b2','#4338ca','#65a30d'],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { position: window.innerWidth < 640 ? 'bottom' : 'right', labels: { boxWidth: 12, padding: 10, font: { size: 11 } } } }
    }
});
</script>
@endpush
@endif
</x-layouts.admin>
