@extends('layouts.admin')

@section('title', 'Dashboard')

@section('content')
<div class="vfh-dash-hero">
    <div>
        <h1 class="vfh-dash-hero__title">Portfolio command centre</h1>
        <p class="vfh-dash-hero__sub">Live lending, deposits, and authorizations for {{ platform_name() }}.</p>
    </div>
    <div class="vfh-dash-hero__actions">
        <a href="{{ route('admin.loans.create') }}" class="fundi-btn fundi-btn--primary">New loan</a>
        <a href="{{ route('admin.reports.portfolio') }}" class="fundi-btn fundi-btn--secondary">Portfolio report</a>
    </div>
</div>

<div class="fundi-stats">
    <div class="fundi-stat fundi-stat--accent">
        <div class="fundi-stat__label">Total Customers</div>
        <div class="fundi-stat__value">{{ number_format($stats['total_customers']) }}</div>
    </div>
    <div class="fundi-stat fundi-stat--accent">
        <div class="fundi-stat__label">Loan Book (Outstanding)</div>
        <div class="fundi-stat__value">{{ money($stats['active_loans_outstanding']) }}</div>
    </div>
    <div class="fundi-stat">
        <div class="fundi-stat__label">Total Deposits</div>
        <div class="fundi-stat__value">{{ money($stats['total_deposits']) }}</div>
    </div>
    <div class="fundi-stat fundi-stat--warning">
        <div class="fundi-stat__label">Pending Authorizations</div>
        <div class="fundi-stat__value">{{ number_format($stats['pending_authorizations']) }}</div>
    </div>
    <div class="fundi-stat">
        <div class="fundi-stat__label">Interest Outstanding</div>
        <div class="fundi-stat__value">{{ money($stats['interest_outstanding']) }}</div>
    </div>
    <div class="fundi-stat">
        <div class="fundi-stat__label">Disbursed MTD</div>
        <div class="fundi-stat__value">{{ money($stats['disbursed_mtd']) }}</div>
    </div>
</div>

<div class="vfh-chart-grid">
    <div class="fundi-card vfh-chart-card">
        <div class="fundi-card__header"><h3>Disbursement trend</h3></div>
        <div class="fundi-card__body fundi-card__body--padded">
            <canvas id="chartTrend" height="140"></canvas>
        </div>
    </div>
    <div class="fundi-card vfh-chart-card">
        <div class="fundi-card__header"><h3>Portfolio by status</h3></div>
        <div class="fundi-card__body fundi-card__body--padded">
            <canvas id="chartPortfolio" height="140"></canvas>
        </div>
    </div>
    <div class="fundi-card vfh-chart-card">
        <div class="fundi-card__header"><h3>Product mix (principal)</h3></div>
        <div class="fundi-card__body fundi-card__body--padded">
            <canvas id="chartProducts" height="140"></canvas>
        </div>
    </div>
</div>

<div class="fundi-card" style="margin-bottom:1.5rem;">
    <div class="fundi-card__header">
        <h3>Loans at a glance — duration &amp; interest</h3>
        <a href="{{ route('admin.loans.index') }}" class="fundi-btn fundi-btn--link fundi-btn--sm">View all</a>
    </div>
    <div class="fundi-card__body fundi-card__body--padded">
        @forelse($loansAtGlance as $loan)
            <div class="vfh-glance">
                <div class="vfh-glance__head">
                    <div>
                        <a href="{{ route('admin.loans.show', $loan) }}" class="vfh-glance__loan">{{ $loan->loan_no }}</a>
                        <div class="text-muted" style="font-size:0.85rem;">
                            {{ $loan->customer->display_name ?? '—' }} · {{ $loan->loanProduct->name ?? '—' }}
                            · {{ money($loan->principal) }}
                        </div>
                    </div>
                    <x-status-badge :status="$loan->status" />
                </div>
                <x-loan-timeline :loan="$loan" :compact="true" />
            </div>
        @empty
            <div class="fundi-empty">No active loans to display.</div>
        @endforelse
    </div>
</div>

<div class="fundi-grid-2">
    <div class="fundi-card">
        <div class="fundi-card__header">
            <h3>Recent Loans</h3>
            <a href="{{ route('admin.loans.index') }}" class="fundi-btn fundi-btn--link fundi-btn--sm">View all</a>
        </div>
        <div class="fundi-card__body">
            <div class="fundi-table-wrap">
                <table class="fundi-table">
                    <thead>
                        <tr>
                            <th>Loan No.</th>
                            <th>Customer</th>
                            <th>Product</th>
                            <th class="num">Principal</th>
                            <th>Timeline</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($recentLoans as $loan)
                            <tr>
                                <td><a href="{{ route('admin.loans.show', $loan) }}">{{ $loan->loan_no }}</a></td>
                                <td>{{ $loan->customer->display_name ?? '—' }}</td>
                                <td>{{ $loan->loanProduct->name ?? '—' }}</td>
                                <td class="num">{{ money($loan->principal) }}</td>
                                <td>
                                    <div class="vfh-mini-progress" title="{{ number_format($loan->durationProgressPercent(), 0) }}% of tenor">
                                        <span style="width:{{ min(100, $loan->durationProgressPercent()) }}%"></span>
                                    </div>
                                    <span class="text-muted" style="font-size:0.75rem;">{{ $loan->tenor_months }} mo</span>
                                </td>
                                <td><x-status-badge :status="$loan->status" /></td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="fundi-empty">No loans yet.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="fundi-card">
        <div class="fundi-card__header"><h3>Portfolio by Status</h3></div>
        <div class="fundi-card__body">
            <div class="fundi-table-wrap">
                <table class="fundi-table">
                    <thead>
                        <tr>
                            <th>Status</th>
                            <th class="num">Count</th>
                            <th class="num">Outstanding</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($portfolioByStatus as $row)
                            <tr>
                                <td><x-status-badge :status="$row->status" /></td>
                                <td class="num">{{ number_format($row->count) }}</td>
                                <td class="num">{{ money($row->outstanding) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="3" class="fundi-empty">No portfolio data.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="fundi-card">
    <div class="fundi-card__header">
        <h3>Recent Customers</h3>
        <a href="{{ route('admin.customers.index') }}" class="fundi-btn fundi-btn--link fundi-btn--sm">View all</a>
    </div>
    <div class="fundi-card__body">
        <div class="fundi-table-wrap">
            <table class="fundi-table">
                <thead>
                    <tr>
                        <th>Customer No.</th>
                        <th>Name</th>
                        <th>Type</th>
                        <th>KYC</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($recentCustomers as $customer)
                        <tr>
                            <td><a href="{{ route('admin.customers.show', $customer) }}">{{ $customer->customer_no }}</a></td>
                            <td>{{ $customer->display_name }}</td>
                            <td>{{ ucfirst($customer->type) }}</td>
                            <td><x-status-badge :status="$customer->kyc_status" /></td>
                            <td><x-status-badge :status="$customer->status" /></td>
                        </tr>
                    @empty
                        <tr><td colspan="5" class="fundi-empty">No customers yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof Chart === 'undefined') return;
    const palette = ['#0E7C7B', '#0B1F33', '#B54708', '#1F7A4C', '#4a5568', '#132d47', '#B42318', '#0a6564'];
    const moneyTick = (v) => '₦' + Number(v).toLocaleString();

    const trend = @json($chartTrend);
    const portfolio = @json($chartPortfolio);
    const products = @json($chartProducts);

    const trendEl = document.getElementById('chartTrend');
    if (trendEl && trend.labels.length) {
        new Chart(trendEl, {
            type: 'bar',
            data: {
                labels: trend.labels,
                datasets: [{
                    label: 'Disbursed',
                    data: trend.amounts,
                    backgroundColor: 'rgba(14, 124, 123, 0.75)',
                    borderRadius: 6,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { ticks: { callback: moneyTick }, grid: { color: 'rgba(11,31,51,0.06)' } },
                    x: { grid: { display: false } }
                }
            }
        });
    }

    const pieEl = document.getElementById('chartPortfolio');
    if (pieEl && portfolio.labels.length) {
        new Chart(pieEl, {
            type: 'doughnut',
            data: {
                labels: portfolio.labels,
                datasets: [{
                    data: portfolio.counts,
                    backgroundColor: palette,
                    borderWidth: 0,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom', labels: { boxWidth: 12, font: { size: 11 } } }
                },
                cutout: '58%'
            }
        });
    }

    const prodEl = document.getElementById('chartProducts');
    if (prodEl && products.labels.length) {
        new Chart(prodEl, {
            type: 'bar',
            data: {
                labels: products.labels,
                datasets: [{
                    label: 'Principal',
                    data: products.principal,
                    backgroundColor: 'rgba(11, 31, 51, 0.8)',
                    borderRadius: 6,
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { ticks: { callback: moneyTick }, grid: { color: 'rgba(11,31,51,0.06)' } },
                    y: { grid: { display: false } }
                }
            }
        });
    }
});
</script>
@endpush
