<x-layouts.admin title="Manage Holdings" activePage="admin-brokerage">

<div class="flex items-center gap-2 text-sm text-on-surface-variant mb-6">
    <a href="{{ route('admin.brokerage.accounts') }}" class="hover:underline">Investment Accounts</a>
    <span>/</span>
    <span class="font-semibold">{{ $account->user->first_name }} {{ $account->user->last_name }} — {{ strtoupper($account->account_type->value) }}</span>
</div>

<div class="flex flex-col sm:flex-row justify-between items-start sm:items-end gap-4 mb-6">
    <div>
        <h2 class="text-2xl font-serif tracking-tight">Manage Holdings</h2>
        <p class="text-sm text-on-surface-variant mt-1">Account: {{ $account->account_number }} | Balance: ${{ number_format($account->balance, 2) }}</p>
    </div>
    @if($account->holdings->count())
    @php $acctTotalPL = $account->holdings->sum('profit_loss'); @endphp
    <div class="text-right">
        <p class="text-xs font-semibold uppercase text-on-surface-variant">Total P/L</p>
        <p class="text-2xl font-bold {{ $acctTotalPL >= 0 ? 'text-green-600' : 'text-red-600' }}">{{ $acctTotalPL >= 0 ? '+' : '' }}${{ number_format($acctTotalPL, 2) }}</p>
    </div>
    @endif
</div>

{{-- Add Holding Form --}}
<div class="bg-surface-container rounded-lg p-6 mb-8">
    <h3 class="font-semibold text-on-surface mb-4">Add New Holding</h3>
    <form method="POST" action="{{ route('admin.brokerage.holdings.store', $account) }}" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 items-end">
        @csrf
        <div>
            <label class="block text-xs font-semibold text-on-surface-variant uppercase mb-1">Name</label>
            <input type="text" name="name" required class="w-full border border-outline-variant/30 rounded px-3 py-2 text-sm" placeholder="S&P 500 Index">
        </div>
        <div>
            <label class="block text-xs font-semibold text-on-surface-variant uppercase mb-1">Type</label>
            <select name="type" required class="w-full border border-outline-variant/30 rounded px-3 py-2 text-sm">
                @foreach($holdingTypes as $ht)
                <option value="{{ $ht->value }}">{{ $ht->label() }}</option>
                @endforeach
            </select>
        </div>
        <div>
            <label class="block text-xs font-semibold text-on-surface-variant uppercase mb-1">Quantity</label>
            <input type="number" name="quantity" step="0.0001" min="0" required class="w-full border border-outline-variant/30 rounded px-3 py-2 text-sm">
        </div>
        <div>
            <label class="block text-xs font-semibold text-on-surface-variant uppercase mb-1">Avg Cost ($)</label>
            <input type="number" name="purchase_price" step="0.01" min="0" required class="w-full border border-outline-variant/30 rounded px-3 py-2 text-sm">
        </div>
        <div>
            <label class="block text-xs font-semibold text-on-surface-variant uppercase mb-1">Current ($)</label>
            <input type="number" name="current_price" step="0.01" min="0" required class="w-full border border-outline-variant/30 rounded px-3 py-2 text-sm">
        </div>
        <div>
            <button type="submit" class="w-full bg-primary text-white py-2 px-4 rounded text-sm font-medium hover:opacity-90">Add</button>
        </div>
    </form>
</div>

{{-- Holdings Table --}}
@if($account->holdings->count())
<div class="bg-surface-container rounded-lg overflow-x-auto mb-6">
    <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">Name</th>
                <th class="px-6 py-4">Type</th>
                <th class="px-6 py-4 text-right">Qty</th>
                <th class="px-6 py-4 text-right">Avg Cost</th>
                <th class="px-6 py-4 text-right">Current</th>
                <th class="px-6 py-4 text-right">P/L</th>
                <th class="px-6 py-4">Actions</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-outline-variant/10">
            @foreach($account->holdings as $h)
            <tr>
                <form method="POST" action="{{ route('admin.brokerage.holdings.update', $h) }}">
                    @csrf @method('PUT')
                    <td class="px-6 py-3"><input type="text" name="name" value="{{ $h->name }}" class="border rounded px-2 py-1 text-sm w-full"></td>
                    <td class="px-6 py-3">
                        <select name="type" class="border rounded px-2 py-1 text-sm">
                            @foreach($holdingTypes as $ht)
                            <option value="{{ $ht->value }}" {{ $h->type === $ht ? 'selected' : '' }}>{{ $ht->label() }}</option>
                            @endforeach
                        </select>
                    </td>
                    <td class="px-6 py-3"><input type="number" name="quantity" step="0.0001" value="{{ $h->quantity }}" class="border rounded px-2 py-1 text-sm w-20 text-right"></td>
                    <td class="px-6 py-3"><input type="number" name="purchase_price" step="0.01" value="{{ $h->purchase_price }}" class="border rounded px-2 py-1 text-sm w-24 text-right"></td>
                    <td class="px-6 py-3"><input type="number" name="current_price" step="0.01" value="{{ $h->current_price }}" class="border rounded px-2 py-1 text-sm w-24 text-right"></td>
                    <td class="px-6 py-3 text-right font-semibold {{ $h->profit_loss >= 0 ? 'text-green-600' : 'text-red-600' }}">${{ number_format($h->profit_loss, 2) }}</td>
                    <td class="px-6 py-3">
                        <div class="flex gap-1">
                            <button type="submit" class="text-xs bg-primary text-white px-2 py-1 rounded">Save</button>
                </form>
                            <form method="POST" action="{{ route('admin.brokerage.holdings.destroy', $h) }}">
                                @csrf @method('DELETE')
                                <button type="submit" class="text-xs bg-red-600 text-white px-2 py-1 rounded" onclick="return confirm('Remove this holding?')">Del</button>
                            </form>
                        </div>
                    </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

{{-- P/L Chart --}}
<div class="bg-surface-container rounded-lg p-6">
    <h3 class="font-semibold text-on-surface mb-4">Profit/Loss Overview</h3>
    <div style="height: 300px;"><canvas id="adminPlChart"></canvas></div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script>
new Chart(document.getElementById('adminPlChart'), {
    type: 'bar',
    data: {
        labels: {!! json_encode($account->holdings->pluck('name')->values()) !!},
        datasets: [{
            label: 'Profit/Loss ($)',
            data: {!! json_encode($account->holdings->pluck('profit_loss')->map(fn($v) => (float)$v)->values()) !!},
            backgroundColor: {!! json_encode($account->holdings->pluck('profit_loss')->map(fn($v) => $v >= 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 } } }
    }
});
</script>
@endpush
@else
<div class="bg-surface-container rounded-lg p-8 text-center text-on-surface-variant">No holdings yet. Use the form above to add investments.</div>
@endif
</x-layouts.admin>
