@extends('layouts.app')

@section('title', 'Dashboard')

@section('content')
@php
    $currency = $business?->currency_symbol ?: ($business?->currency ?: '');
    $money = fn ($value) => trim($currency.' '.number_format((float) $value, 2));
    $isSuperAdministrator = $isSystemWide;
    $kpis = [];
    $systemCards = [];
    $portfolioRows = [];
    $accountBalanceLabels = [
        'cash' => 'Cash',
        'mobile_money' => 'Mobile Money',
        'bank' => 'Bank',
        'other' => 'Other',
    ];

    if (! empty($dashboard)) {
        $m = $dashboard['metrics'];
        $system = $dashboard['system_overview'];
        $portfolio = $dashboard['portfolio_performance'];
        $portfolioMax = max(
            1,
            (float) $portfolio['total_outstanding'],
            (float) $portfolio['overdue'],
            (float) $portfolio['scheduled_due'],
            (float) $portfolio['collected'],
        );

        $systemCards = [
            ['Branches', number_format((int) $system['branches']), number_format((int) $system['active_branches']).' active'],
            ['Customers', number_format((int) $system['customers']), number_format((int) $system['new_customers']).' new · '.$periodLabel],
            ['Staff', number_format((int) $system['staff']), 'Users assigned to this scope'],
            ['All Loans', number_format((int) $system['loans']), 'Complete loan book'],
            ['Pending Applications', number_format((int) $system['pending_approvals']), 'Require workflow attention'],
            ['Ready to Disburse', number_format((int) $system['ready_for_disbursement']), 'Approved and awaiting funding'],
            ['Overdue Loans', number_format((int) $system['overdue_loans']), 'Active loans currently in arrears'],
            ['Open Alerts', number_format((int) $system['open_alerts']), 'Unresolved management alerts'],
        ];

        $kpis = [
            ['Total Available Funds', $money($m['available_funds']), 'Reconstructed closing balances'],
            ['Outstanding Principal', $money($m['outstanding_principal']), 'Current active portfolio'],
            ['Expected Interest', $money($m['expected_interest']), 'Outstanding interest receivable'],
            [$period === 'today' ? 'Collections Today' : 'Collections · '.$periodLabel, $money($m['collections']), 'Actual account-ledger collections'],
            [$period === 'today' ? 'Disbursements Today' : 'Disbursements · '.$periodLabel, $money($m['disbursements']), 'Actual loan funding movements'],
            [$period === 'today' ? 'Expenses Today' : 'Expenses · '.$periodLabel, $money($m['expenses']), 'Approved operating expenses'],
            ['Net Result · '.$periodLabel, $money($m['period_profit']), 'Income less expenses for selected period'],
            ['Overdue Amount', $money($m['overdue_amount']), 'Current arrears exposure'],
            ['Active Loans', number_format((int) $m['active_loans']), 'Current live loan portfolio'],
            ['Completed Loans', number_format((int) $m['completed_loans']), 'All completed loan history'],
            ['Written-Off Portfolio', $money($m['written_off_portfolio']), 'Remaining recoverable write-off balance'],
            ['Profit This Month', $money($m['profit_this_month']), 'Current-month P&L'],
        ];

        $portfolioRows = [
            ['Total outstanding', $portfolio['total_outstanding']],
            ['Current overdue', $portfolio['overdue']],
            ['Scheduled due · '.$periodLabel, $portfolio['scheduled_due']],
            ['Collected · '.$periodLabel, $portfolio['collected']],
        ];
    }
@endphp

@if (! $managementDashboard)
    <x-ui.page-toolbar title="Workspace" description="Your branch operations and available modules." :breadcrumbs="[['label'=>'Dashboard']]" />

    <div class="mf-stat-grid mb-4">
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Signed in as</div>
            <div class="mt-1 text-lg font-semibold">{{ auth()->user()->name }}</div>
            <div class="text-xs text-muted-foreground">{{ auth()->user()->employee_number ?: 'Staff account' }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Primary branch</div>
            <div class="mt-1 text-lg font-semibold">{{ auth()->user()->primaryBranch?->name ?? 'Not assigned' }}</div>
            <div class="text-xs text-muted-foreground">{{ auth()->user()->position ?: '—' }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Role</div>
            <div class="mt-1 text-lg font-semibold">{{ auth()->user()->roles->pluck('display_name')->join(', ') ?: 'No role assigned' }}</div>
            <div class="text-xs text-muted-foreground">Management figures require report access.</div>
        </div>
    </div>

    <div class="mf-card">
        <div class="mf-card-header">
            <h2 class="mf-card-title">Available operations</h2>
            <p class="mf-card-subtitle">Shortcuts are shown only for permissions assigned to your account.</p>
        </div>
        <div class="mf-card-body flex flex-wrap gap-2">
            @if (auth()->user()->can('customers.view'))
                <a class="mf-btn" href="{{ route('customers.index') }}">Customers</a>
            @endif
            @if (auth()->user()->can('loans.view'))
                <a class="mf-btn" href="{{ route('loans.index') }}">Loans</a>
            @endif
            @if (auth()->user()->can('payments.receive'))
                <a class="mf-btn" href="{{ route('loan-payments.index') }}">Loan Payments</a>
            @endif
            @if (auth()->user()->can('arrears.view'))
                <a class="mf-btn" href="{{ route('arrears.index') }}">Arrears</a>
            @endif
            @if (auth()->user()->can('collateral.view'))
                <a class="mf-btn" href="{{ route('collateral.index') }}">Collateral</a>
            @endif
            @if (auth()->user()->can('expenses.view'))
                <a class="mf-btn" href="{{ route('expenses.index') }}">Expenses</a>
            @endif
            @if (auth()->user()->can('accounts.view'))
                <a class="mf-btn" href="{{ route('accounts.index') }}">Financial Accounts</a>
            @endif
        </div>
    </div>
@else
    <x-ui.page-toolbar
        title="Management Dashboard"
        :description="$isSuperAdministrator ? 'Super administrator system-wide financial, portfolio, branch and operational oversight.' : 'Financial and portfolio performance across your accessible branches.'"
        :breadcrumbs="[['label'=>'Dashboard']]"
    >
        <x-slot:actions>
            @if ($isSuperAdministrator)
                <a class="mf-btn" href="{{ route('management-alerts.index') }}">Management Alerts</a>
                <a class="mf-btn" href="{{ route('admin.audit.index') }}">Audit Log</a>
            @endif
            <a class="mf-btn" href="{{ route('reports.index') }}">Financial Reports</a>
            <a class="mf-btn" href="{{ route('loan-branch-reports.index') }}">Loan & Branch Reports</a>
        </x-slot:actions>
    </x-ui.page-toolbar>

    <div class="mf-card mb-4">
        <form method="GET" action="{{ route('dashboard') }}" class="mf-card-body mf-dashboard-grid">
            <div>
                <div class="mf-split-grid">
                    <div>
                        <label class="mf-label">Period</label>
                        <select class="mf-select" name="period">
                            <option value="today" @selected($period === 'today')>Today</option>
                            <option value="yesterday" @selected($period === 'yesterday')>Yesterday</option>
                            <option value="this-week" @selected($period === 'this-week')>This Week</option>
                            <option value="this-month" @selected($period === 'this-month')>This Month</option>
                            <option value="this-year" @selected($period === 'this-year')>This Year</option>
                            <option value="custom" @selected($period === 'custom')>Custom Range</option>
                        </select>
                    </div>
                    <div class="mf-split-grid">
                        <div>
                            <label class="mf-label">From</label>
                            <input class="mf-input" type="date" name="from" value="{{ $period === 'custom' ? $from : '' }}">
                        </div>
                        <div>
                            <label class="mf-label">To</label>
                            <input class="mf-input" type="date" name="to" value="{{ $period === 'custom' ? $to : '' }}">
                        </div>
                    </div>
                </div>
                <div class="mt-2 text-[11px] text-muted-foreground">
                    Current portfolio figures remain live snapshots; transaction and P&amp;L figures follow the selected period.
                </div>
            </div>

            <div>
                @php
                    $branchFilterIds = collect(request()->input('branch_ids', []))
                        ->map(fn ($id) => (int) $id)
                        ->unique()
                        ->values();
                    $branchFilterSelection = $branches->whereIn('id', $branchFilterIds)->values();
                @endphp
                <div class="mb-1 flex items-center justify-between gap-2">
                    <label class="mf-label mb-0">Branches</label>
                    <span class="text-[11px] text-muted-foreground">
                        {{ $branchFilterIds->isEmpty() ? 'All branches' : $branchFilterIds->count().' selected' }}
                    </span>
                </div>
                <details class="mf-columns-menu w-full" data-dashboard-branch-picker>
                    <summary class="mf-select cursor-pointer w-full" aria-label="Select dashboard branches">
                        {{ $branchFilterSelection->isEmpty() ? 'All branches' : ($branchFilterSelection->count() === 1 ? $branchFilterSelection->first()->name : $branchFilterSelection->count().' branches selected') }}
                    </summary>
                    <div class="mf-columns-popover" style="min-width:100%;width:max-content;max-width:min(360px,90vw);">
                        <div class="mf-columns-title">Select branches</div>
                        @foreach ($branches as $branch)
                            <label>
                                <input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}" @checked($branchFilterIds->contains($branch->id))>
                                <span>{{ $branch->name }}</span>
                            </label>
                        @endforeach
                        <div class="px-3 pb-2 text-[11px] text-muted-foreground">No specific selection means all accessible branches.</div>
                    </div>
                </details>
                <div class="mt-1 text-[11px] text-muted-foreground">Choose one or more branches to narrow the dashboard; leave all unchecked for all branches.</div>
                <div class="mt-2 flex items-center gap-2">
                    <a class="mf-btn" href="{{ route('dashboard') }}">Reset</a>
                    <button class="mf-btn mf-btn-primary" style="flex:1 1 auto;" type="submit">Apply Dashboard Filters</button>
                </div>
            </div>
        </form>
    </div>

    @if (! $dashboard)
        <div class="mf-card mf-card-body py-10 text-center">
            <div class="text-base font-semibold">No branch is assigned</div>
            <div class="mt-1 text-sm text-muted-foreground">Assign at least one branch before management figures can be calculated.</div>
        </div>
    @else
        <div class="mb-3 flex flex-wrap items-center justify-between gap-2">
            <div>
                <div class="text-sm font-semibold">{{ $periodLabel }}</div>
                <div class="text-xs text-muted-foreground">{{ $branchFilterIds->isEmpty() ? 'All branches' : $selectedBranches->pluck('name')->join(', ') }}</div>
            </div>
            @if ($isSuperAdministrator)
                <span class="mf-badge mf-badge-success">Full system oversight</span>
            @else
                <span class="mf-badge mf-badge-muted">Assigned branch scope</span>
            @endif
        </div>

        <section class="mb-4" aria-label="System overview">
            <div class="mb-2 flex items-end justify-between gap-3">
                <div>
                    <div class="text-sm font-semibold">{{ $isSuperAdministrator ? 'System Overview' : 'Scope Overview' }}</div>
                    <div class="text-xs text-muted-foreground">Operational counts across the selected branches.</div>
                </div>
            </div>
            <div class="mf-stat-grid">
                @foreach ($systemCards as $card)
                    <article class="mf-card mf-card-body">
                        <div class="text-xs font-medium text-muted-foreground">{{ $card[0] }}</div>
                        <div class="mt-1 text-xl font-semibold tracking-tight">{{ $card[1] }}</div>
                        <div class="mt-1 text-[11px] text-muted-foreground">{{ $card[2] }}</div>
                    </article>
                @endforeach
            </div>
        </section>

        <section class="mb-4" aria-label="Management KPIs">
            <div class="mb-2">
                <div class="text-sm font-semibold">Financial & Portfolio KPIs</div>
                <div class="text-xs text-muted-foreground">Key figures reconciled to financial and loan reports.</div>
            </div>
            <div class="mf-stat-grid">
                @foreach ($kpis as $kpi)
                    <article class="mf-card mf-card-body">
                        <div class="text-xs font-medium text-muted-foreground">{{ $kpi[0] }}</div>
                        <div class="mt-1 text-xl font-semibold tracking-tight">{{ $kpi[1] }}</div>
                        <div class="mt-1 text-[11px] text-muted-foreground">{{ $kpi[2] }}</div>
                    </article>
                @endforeach
            </div>
        </section>

        <section class="mb-4">
            <div class="mb-2 text-sm font-semibold">Account Balances</div>
            <div class="mf-stat-grid">
                @foreach ($accountBalanceLabels as $key => $label)
                    <div class="mf-card mf-card-body">
                        <div class="text-xs text-muted-foreground">{{ $label }}</div>
                        <div class="mt-1 text-lg font-semibold">{{ $money($dashboard['account_balances'][$key]) }}</div>
                    </div>
                @endforeach
            </div>
        </section>

        <section class="mf-split-grid mb-4">
            <article class="mf-card">
                <div class="mf-card-header">
                    <h2 class="mf-card-title">Collections & Disbursements</h2>
                    <p class="mf-card-subtitle">Actual account-ledger movements · {{ $periodLabel }}</p>
                </div>
                <div class="mf-card-body">
                    <div style="overflow-x:auto;">
                        <div class="mf-chart" style="min-width: 540px;">
                            @foreach ($dashboard['flow_series'] as $point)
                                <div class="mf-chart-col" title="{{ $point['label'] }} · Collections {{ $money($point['collections']) }} · Disbursements {{ $money($point['disbursements']) }}">
                                    <div class="mf-chart-bar-wrap" style="gap:3px;">
                                        <span class="mf-chart-bar" style="height: {{ max(2, $point['collections_pct']) }}%;"></span>
                                        <span class="mf-chart-bar" style="height: {{ max(2, $point['disbursements_pct']) }}%; background: var(--muted-foreground); opacity: .38;"></span>
                                    </div>
                                    <span class="mf-chart-label">{{ $point['label'] }}</span>
                                </div>
                            @endforeach
                        </div>
                    </div>
                    <div class="mt-3 flex flex-wrap items-center justify-between gap-3 text-[11px] text-muted-foreground">
                        <span>■ Collections</span>
                        <span style="opacity:.65;">■ Disbursements</span>
                        <span>{{ count($dashboard['flow_series']) }} time buckets</span>
                    </div>
                </div>
            </article>

            <article class="mf-card">
                <div class="mf-card-header">
                    <h2 class="mf-card-title">Income vs Expenses</h2>
                    <p class="mf-card-subtitle">Recognized P&amp;L movements · {{ $periodLabel }}</p>
                </div>
                <div class="mf-card-body">
                    <div style="overflow-x:auto;">
                        <div class="mf-chart" style="min-width: 540px;">
                            @foreach ($dashboard['income_expense_series'] as $point)
                                <div class="mf-chart-col" title="{{ $point['label'] }} · Income {{ $money($point['income']) }} · Expenses {{ $money($point['expenses']) }}">
                                    <div class="mf-chart-bar-wrap" style="gap:3px;">
                                        <span class="mf-chart-bar" style="height: {{ max(2, $point['income_pct']) }}%;"></span>
                                        <span class="mf-chart-bar" style="height: {{ max(2, $point['expenses_pct']) }}%; background: var(--destructive); opacity: .42;"></span>
                                    </div>
                                    <span class="mf-chart-label">{{ $point['label'] }}</span>
                                </div>
                            @endforeach
                        </div>
                    </div>
                    <div class="mt-3 flex flex-wrap items-center justify-between gap-3 text-[11px] text-muted-foreground">
                        <span>■ Income</span>
                        <span style="color:var(--destructive);">■ Expenses</span>
                        <span>Net {{ $money($dashboard['period_pnl']['net_profit']) }}</span>
                    </div>
                </div>
            </article>
        </section>

        <section class="mf-split-grid mb-4">
            <article class="mf-card">
                <div class="mf-card-header">
                    <h2 class="mf-card-title">Portfolio Performance</h2>
                    <p class="mf-card-subtitle">Current portfolio quality with selected-period repayment performance.</p>
                </div>
                <div class="mf-card-body space-y-4">
                    @foreach ($portfolioRows as $row)
                        <div>
                            <div class="mb-1 flex items-center justify-between gap-3 text-xs">
                                <span>{{ $row[0] }}</span>
                                <span class="font-medium">{{ $money($row[1]) }}</span>
                            </div>
                            <div class="mf-progress">
                                <span style="width: {{ min(100, round(((float) $row[1] / $portfolioMax) * 100)) }}%;"></span>
                            </div>
                        </div>
                    @endforeach
                    <div class="border-t border-border pt-3 mf-split-grid">
                        <div>
                            <div class="text-xs text-muted-foreground">Collection rate</div>
                            <div class="mt-1 text-lg font-semibold">{{ number_format((float) $portfolio['collection_rate'], 2) }}%</div>
                        </div>
                        <div>
                            <div class="text-xs text-muted-foreground">Portfolio at risk</div>
                            <div class="mt-1 text-lg font-semibold">{{ number_format((float) $portfolio['portfolio_at_risk'], 2) }}%</div>
                        </div>
                    </div>
                </div>
            </article>

            <article class="mf-card">
                <div class="mf-card-header">
                    <h2 class="mf-card-title">Loan Portfolio Mix</h2>
                    <p class="mf-card-subtitle">Status distribution for {{ number_format((int) $dashboard['loan_status_distribution']['total']) }} loans.</p>
                </div>
                <div class="mf-card-body space-y-4">
                    @foreach ($dashboard['loan_status_distribution']['rows'] as $row)
                        <div>
                            <div class="mb-1 flex items-center justify-between gap-3 text-xs">
                                <span>{{ $row['label'] }}</span>
                                <span class="font-medium">{{ number_format((int) $row['count']) }} · {{ $row['percentage'] }}%</span>
                            </div>
                            <div class="mf-progress">
                                <span style="width: {{ $row['percentage'] }}%;"></span>
                            </div>
                        </div>
                    @endforeach
                </div>
            </article>
        </section>

        <section class="mf-card mb-4">
            <div class="mf-card-header">
                <h2 class="mf-card-title">Branch Performance</h2>
                <p class="mf-card-subtitle">Collections, disbursements, portfolio size and collection rate by branch.</p>
            </div>
            <div class="mf-table-wrap">
                <table class="mf-table">
                    <thead>
                        <tr>
                            <th>Branch</th>
                            <th class="text-right">Collections</th>
                            <th class="text-right">Disbursed</th>
                            <th class="text-right">Outstanding</th>
                            <th class="text-right">Collection Rate</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($dashboard['branch_performance'] as $row)
                            <tr>
                                <td class="font-medium">{{ $row['branch'] }}</td>
                                <td class="text-right">{{ $money($row['collections']) }}</td>
                                <td class="text-right">{{ $money($row['disbursed_amount']) }}</td>
                                <td class="text-right">{{ $money($row['total_outstanding']) }}</td>
                                <td class="text-right font-semibold">{{ number_format((float) $row['collection_rate'], 2) }}%</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted-foreground">No branch performance data in this scope.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </section>

        <section class="mf-split-grid mb-4">
            <article class="mf-card">
                <div class="mf-card-header flex items-start justify-between gap-3">
                    <div>
                        <h2 class="mf-card-title">Management Alerts</h2>
                        <p class="mf-card-subtitle">{{ $dashboard['management_alerts']['open'] }} open · {{ $dashboard['management_alerts']['acknowledged'] }} acknowledged</p>
                    </div>
                    @if (auth()->user()->can('management-alerts.view'))
                        <a class="mf-btn" href="{{ route('management-alerts.index') }}">View All</a>
                    @endif
                </div>
                <div class="mf-card-body">
                    @forelse ($dashboard['management_alerts']['items'] as $alert)
                        <div class="mf-activity">
                            <span class="mf-activity-dot"></span>
                            <div class="min-w-0 flex-1">
                                <div class="flex flex-wrap items-center justify-between gap-2">
                                    <div class="text-sm font-medium">{{ $alert['title'] }}</div>
                                    <span class="mf-badge {{ $alert['severity'] === 'critical' || $alert['severity'] === 'high' ? 'mf-badge-danger' : ($alert['severity'] === 'medium' ? 'mf-badge-warning' : 'mf-badge-muted') }}">{{ str($alert['severity'])->headline() }}</span>
                                </div>
                                <div class="mt-1 text-xs text-muted-foreground">{{ $alert['message'] }}</div>
                                <div class="mt-1 text-[11px] text-muted-foreground">{{ $alert['branch'] ?: 'System' }} · {{ $alert['occurred_at']?->diffForHumans() }}</div>
                            </div>
                        </div>
                    @empty
                        <div class="py-8 text-center text-sm text-muted-foreground">No active management alerts.</div>
                    @endforelse
                </div>
            </article>

            <article class="mf-card">
                <div class="mf-card-header flex items-start justify-between gap-3">
                    <div>
                        <h2 class="mf-card-title">Recent System Activity</h2>
                        <p class="mf-card-subtitle">Latest auditable actions in the selected branch scope.</p>
                    </div>
                    @if ($isSuperAdministrator)
                        <a class="mf-btn" href="{{ route('admin.audit.index') }}">Audit Log</a>
                    @endif
                </div>
                <div class="mf-card-body">
                    @forelse ($dashboard['recent_activity'] as $activity)
                        <div class="mf-activity">
                            <span class="mf-activity-dot"></span>
                            <div class="min-w-0 flex-1">
                                <div class="text-sm font-medium">{{ $activity['action'] }} {{ $activity['subject'] ?: 'Record' }}</div>
                                <div class="mt-1 text-xs text-muted-foreground">{{ $activity['user'] }} · {{ $activity['branch'] ?: 'System' }}</div>
                                <div class="mt-1 text-[11px] text-muted-foreground">{{ $activity['created_at']?->diffForHumans() }}</div>
                            </div>
                        </div>
                    @empty
                        <div class="py-8 text-center text-sm text-muted-foreground">No recent auditable activity in this scope.</div>
                    @endforelse
                </div>
            </article>
        </section>

        <section class="mf-card">
            <div class="mf-card-header">
                <h2 class="mf-card-title">Financial Account Detail</h2>
                <p class="mf-card-subtitle">Balances reconstructed from permanent financial account transactions.</p>
            </div>
            <div class="mf-table-wrap">
                <table class="mf-table">
                    <thead>
                        <tr>
                            <th>Account</th>
                            <th>Type</th>
                            <th>Branch</th>
                            <th class="text-right">Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($dashboard['account_summaries'] as $summary)
                            <tr>
                                <td>{{ $summary['account']->name }}</td>
                                <td>{{ str($summary['account']->account_type)->replace('_', ' ')->title() }}</td>
                                <td>{{ $summary['account']->branch?->name }}</td>
                                <td class="text-right font-semibold">{{ $money($summary['closing_balance']) }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="4" class="text-center text-muted-foreground">No financial accounts in this scope.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </section>
    @endif
@endif
@endsection