@php
    use App\Enum\Dsar\DsarStatus;

    /**
     * Week-on-week delta badge. $lowerIsBetter inverts the colouring for metrics
     * like response time, where a fall is an improvement.
     */
    $trend = function ($current, $previous, bool $lowerIsBetter = false) {
        if (!$previous) {
            return null;                         // no baseline — nothing meaningful to show
        }
        $change = round((($current - $previous) / $previous) * 100, 1);
        $good   = $lowerIsBetter ? $change <= 0 : $change >= 0;

        return [
            'change' => $change,
            'class'  => $good ? 'text-success' : 'text-danger',
            'icon'   => $change >= 0 ? 'bi-arrow-up-right' : 'bi-arrow-down-right',
        ];
    };
@endphp

<div>
    <div class="row mb-4 align-items-center">
        <div class="col">
            <h2 class="fw-bold mb-0">
                <i class="bi bi-bar-chart-line text-primary me-2"></i>DSAR Report
            </h2>
            <p class="text-muted mt-1 mb-0">Overview of all Data Subject Access Requests</p>
        </div>
    </div>

    {{-- Headline cards --}}
    <div class="row g-3 mb-4">
        @php $sentTrend = $trend($sentThisWeek, $sentLastWeek); @endphp
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Total Sent (All Time)</p>
                    <h3 class="fw-bold mb-0">{{ number_format($totalAll) }}</h3>
                    <small class="text-muted">{{ $totalMonth }} this month</small>
                    <div class="small mt-1">
                        @if($sentTrend)
                            <span class="{{ $sentTrend['class'] }}">
                                <i class="bi {{ $sentTrend['icon'] }}"></i>
                                {{ abs($sentTrend['change']) }}%
                            </span>
                        @endif
                        <span class="text-muted">{{ $sentThisWeek }} this week vs {{ $sentLastWeek }} last week</span>
                    </div>
                </div>
            </div>
        </div>

        @php $completedTrend = $trend($completedThisWeek, $completedLastWeek); @endphp
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Completed</p>
                    <h3 class="fw-bold mb-0 text-success">{{ number_format($completedCount) }}</h3>
                    <small class="text-muted">
                        @if($totalAll > 0)
                            {{ round(($completedCount / $totalAll) * 100, 1) }}% completion rate
                        @else
                            &mdash;
                        @endif
                    </small>
                    <div class="small mt-1">
                        @if($completedTrend)
                            <span class="{{ $completedTrend['class'] }}">
                                <i class="bi {{ $completedTrend['icon'] }}"></i>
                                {{ abs($completedTrend['change']) }}%
                            </span>
                        @endif
                        <span class="text-muted">{{ $completedThisWeek }} this week vs {{ $completedLastWeek }} last week</span>
                    </div>
                </div>
            </div>
        </div>

        @php $avgTrend = $trend($avgThisWeek, $avgLastWeek, lowerIsBetter: true); @endphp
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-body">
                    <p class="label-upper mb-1">Avg Response Time</p>
                    <h3 class="fw-bold mb-0">
                        {{ $avgResponseDays ? round($avgResponseDays, 1) . ' days' : '—' }}
                    </h3>
                    <small class="text-muted">From send to response</small>
                    <div class="small mt-1">
                        @if($avgTrend)
                            <span class="{{ $avgTrend['class'] }}">
                                <i class="bi {{ $avgTrend['icon'] }}"></i>
                                {{ abs($avgTrend['change']) }}%
                            </span>
                        @endif
                        <span class="text-muted">
                            {{ $avgThisWeek ? round($avgThisWeek, 1) . 'd' : '—' }} this week
                            vs {{ $avgLastWeek ? round($avgLastWeek, 1) . 'd' : '—' }} last week
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        {{-- Status Breakdown — every status in the enum --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-pie-chart me-2 text-primary"></i>Status Breakdown
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Status</th>
                                <th class="text-end">Count</th>
                                <th class="text-end">%</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach(DsarStatus::cases() as $case)
                                @php $count = $byStatus->get($case->value, 0); @endphp
                                <tr>
                                    <td>
                                        <span class="badge {{ DsarStatus::badgeFor($case->value) }}">
                                            {{ DsarStatus::label($case->value) }}
                                        </span>
                                    </td>
                                    <td class="text-end">{{ $count }}</td>
                                    <td class="text-end text-muted small">
                                        {{ $grandTotal > 0 ? round(($count / $grandTotal) * 100, 1) : 0 }}%
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="card-footer bg-light small text-muted">
                    Percentages are of all {{ number_format($grandTotal) }} DSARs, including drafts.
                </div>
            </div>
        </div>

        {{-- Response Types — outcome statuses as a share of DSARs responded to --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-reply-all me-2 text-primary"></i>Response Types
                </div>
                <div class="card-body">
                    @if($totalResponded > 0)
                        @foreach($responded as $status)
                            @php
                                $count = $byStatus->get($status, 0);
                                $pct   = round(($count / $totalResponded) * 100);
                            @endphp
                            <div class="mb-2">
                                <div class="d-flex justify-content-between small mb-1">
                                    <span>{{ DsarStatus::label($status) }}</span>
                                    <span class="fw-semibold">{{ $count }} ({{ $pct }}%)</span>
                                </div>
                                <div class="progress" style="height:8px;">
                                    <div class="progress-bar {{ DsarStatus::badgeFor($status) }}" style="width:{{ $pct }}%"></div>
                                </div>
                            </div>
                        @endforeach
                    @else
                        <p class="text-muted small mb-0">No responses received yet.</p>
                    @endif
                </div>
                <div class="card-footer bg-light small text-muted">
                    % of the {{ number_format($totalResponded) }} DSARs that have had a response.
                    Failed sends are not responses and are excluded.
                </div>
            </div>
        </div>

        {{-- Sent per month, rolling 6 months --}}
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header fw-semibold">
                    <i class="bi bi-calendar3 me-2 text-primary"></i>DSARs Sent per Month
                </div>
                <div class="card-body">
                    {{--
                        wire:ignore — the sort/search filters below are wire:model.live, so
                        Livewire re-renders this component and would otherwise morph the
                        canvas out from under Chart.js. @script only runs once.
                        maintainAspectRatio:false, so the chart sizes to this box.
                    --}}
                    <div wire:ignore style="height: 200px;">
                        <canvas id="dsarSentMonthlyChart"></canvas>
                    </div>
                </div>
                <div class="card-footer bg-light small text-muted">
                    DSARs that left the pre-send stage, by the month they were created.
                </div>
            </div>
        </div>
    </div>

    {{-- DSARs by Target --}}
    <div class="card">
        <div class="card-header bg-white d-flex flex-wrap gap-2 align-items-center">
            <span class="fw-semibold me-auto">
                <i class="bi bi-bullseye me-2 text-primary"></i>DSARs by Target
            </span>

            <select class="form-select form-select-sm w-auto" wire:model.live="sort">
                <option value="outstanding">Sort: Outstanding</option>
                <option value="oldest">Sort: Oldest Outstanding</option>
                <option value="backlog">Sort: Stated Backlog</option>
                <option value="avg">Sort: Avg Response Days</option>
                <option value="sent">Sort: Total Sent</option>
            </select>

            <input type="text"
                   class="form-control form-control-sm w-auto"
                   style="min-width: 220px"
                   wire:model.live.debounce.300ms="targetSearch"
                   placeholder="Search institution…">
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Institution</th>
                            <th class="text-end" title="DSARs sent but not yet completed">Outstanding</th>
                            <th class="text-end" title="Days since oldest outstanding DSAR was created">Oldest (days)</th>
                            <th class="text-end" title="Average days from send to response (our data)">Avg Response</th>
                            <th class="text-end" title="Backlog the institution has publicly stated">Stated Backlog</th>
                            <th class="text-end">Sent</th>
                            <th class="text-end">Completed</th>
                            <th class="text-end">Completion %</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($byTarget as $row)
                            @php
                                $highBacklog  = $row->stated_backlog !== null && $row->stated_backlog >= 100;
                                $agedOutstand = $row->oldest_age_days !== null && $row->oldest_age_days >= 60;
                            @endphp
                            <tr class="{{ $row->outstanding > 0 && ($highBacklog || $agedOutstand) ? 'table-warning' : '' }}">
                                <td>
                                    @if($row->institution)
                                        <a wire:navigate href="{{ route('institutions.show', $row->institution) }}"
                                           class="fw-semibold">
                                            {{ $row->display_name }}
                                        </a>
                                    @else
                                        <span class="text-muted fst-italic">{{ $row->display_name }}</span>
                                    @endif
                                </td>
                                <td class="text-end">
                                    @if($row->outstanding > 0)
                                        <span class="badge bg-warning text-dark">{{ $row->outstanding }}</span>
                                        @if($row->institution)
                                            <a href="{{ route('dsars.report.institution', $row->institution) }}"
                                               class="btn btn-outline-secondary btn-sm py-0 ms-1"
                                               title="Drill-down">
                                                <i class="bi bi-zoom-in"></i>
                                            </a>
                                        @endif
                                    @else
                                        <span class="text-muted">0</span>
                                    @endif
                                </td>
                                <td class="text-end {{ $agedOutstand ? 'text-danger fw-semibold' : '' }}">
                                    {{ $row->oldest_age_days !== null ? $row->oldest_age_days : '—' }}
                                </td>
                                <td class="text-end">
                                    {{ $row->avg_response_days !== null ? $row->avg_response_days . ' d' : '—' }}
                                </td>
                                <td class="text-end">
                                    @if($row->stated_backlog !== null)
                                        <span class="fw-semibold {{ $highBacklog ? 'text-danger' : '' }}">
                                            {{ number_format($row->stated_backlog) }}
                                        </span>
                                        @if($row->backlog_updated_at)
                                            <div class="text-muted small" title="{{ $row->backlog_updated_at }}">
                                                as of {{ $row->backlog_updated_at->format('d M Y') }}
                                            </div>
                                        @endif
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td class="text-end">{{ $row->total_sent }}</td>
                                <td class="text-end">{{ $row->total_completed }}</td>
                                <td class="text-end">
                                    <div class="d-flex align-items-center justify-content-end gap-2">
                                        <div class="progress flex-grow-1" style="height:6px;max-width:80px;">
                                            <div class="progress-bar bg-success" style="width:{{ $row->completion_rate }}%"></div>
                                        </div>
                                        <small>{{ $row->completion_rate }}%</small>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="8" class="text-muted text-center py-3">No DSARs found.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer bg-light small text-muted">
            Rows shaded amber have outstanding DSARs at a target with either a large stated backlog (≥100) or an oldest outstanding DSAR 60+ days old.
            Set each institution's <strong>Stated SAR Backlog</strong> on its edit page to sharpen response-time predictions.
        </div>
    </div>

    @script
    <script>
        const sentByMonth = @json($sentByMonth);

        let dsarSentChart = null;

        // Deferred so the canvas has been laid out and Chart.js can size to it.
        setTimeout(() => {
            const canvas = document.getElementById('dsarSentMonthlyChart');
            if (!canvas || dsarSentChart) {
                return;
            }

            dsarSentChart = new Chart(canvas, {
                type: 'bar',
                data: {
                    labels: sentByMonth.map(m => m.label),
                    datasets: [{
                        label: 'DSARs sent',
                        data: sentByMonth.map(m => m.total),
                        borderRadius: 4,
                    }],
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false }, tooltip: { padding: 10 } },
                    scales: {
                        x: { grid: { display: false } },
                        y: { beginAtZero: true, ticks: { precision: 0 } },
                    },
                },
            });
        }, 0);
    </script>
    @endscript
</div>
