<?php

namespace App\Components\Report;

use App\Models\LeadSource\LeadSource;
use App\Models\Solicitor\Solicitor;
use App\Services\Dashboard\DashboardMetrics;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * Pipeline KPIs report — the live "where are we right now" overview: current
 * backlog / snapshot stat cards up top, then per-stage flow tables (Day / Week /
 * Month with previous-period comparison). Every metric is computed by the shared
 * App\Services\Dashboard\DashboardMetrics service.
 *
 * This is a standalone report, separate from the login dashboard.
 */
class PipelineKpis extends Component
{
    use AuthorizesRequests;

    #[Url]
    public ?int $leadSourceId = null;

    public function mount(): void
    {
        $this->authorize('reports.trends');
    }

    public function render()
    {
        $solicitorId = app(Solicitor::class)?->id;

        $metrics = new DashboardMetrics(
            $solicitorId,
            $this->leadSourceId ?: null,
        );

        // Deltas compare against per-solicitor, all-lead-source snapshots, so they
        // are only meaningful (and shown) in the "All Lead Sources" view.
        $showDeltas = $this->leadSourceId === null;

        $now = Carbon::now();
        $periods = [
            'today'     => [Carbon::today(), $now],
            'week'      => [$now->copy()->startOfWeek(), $now],
            'month'     => [$now->copy()->startOfMonth(), $now],
            'histWeek'  => [$now->copy()->subWeek()->startOfWeek(), $now->copy()->subWeek()->endOfWeek()],
            'histMonth' => [$now->copy()->subMonth()->startOfMonth(), $now->copy()->subMonth()->endOfMonth()],
        ];

        $across = fn (callable $calc): array => collect($periods)
            ->map(fn (array $range) => $calc($range[0], $range[1]))
            ->all();

        $throughput = fn (callable $calc, string $label, string $sub = '', string $note = ''): array => [
            'type' => 'throughput', 'label' => $label, 'sub' => $sub, 'note' => $note,
            'values' => $across($calc),
        ];

        $derived = fn (callable $calc, string $type, string $label, string $note = ''): array => [
            'type' => $type, 'label' => $label, 'sub' => '', 'note' => $note,
            'values' => $across($calc),
        ];

        // Point-in-time stat card. $fivePm marks the two 5pm-recorded figures;
        // $dir controls trend colouring ('down' fewer-better, 'up' more-better,
        // 'neutral' no judgement).
        $card = function (int $value, string $key, string $label, string $accent, string $icon, string $note = '', bool $fivePm = false, string $dir = 'down') use ($metrics, $showDeltas): array {
            return [
                'label' => $label, 'value' => $value, 'accent' => $accent, 'icon' => $icon,
                'note' => $note, 'fivePm' => $fivePm, 'dir' => $dir,
                'series' => $showDeltas ? $metrics->snapshotSeries($key, $value, 14) : null,
            ];
        };

        $currentCards = [
            $card($metrics->currentlyInStatus(DashboardMetrics::STATUS_WELCOME_CALL), 'at_welcome_call', 'At Welcome Call', 'primary', 'mdi-phone-in-talk', '', false, 'neutral'),
            $card($metrics->currentlyInStatus(DashboardMetrics::STATUS_MISSING_ID), 'missing_id_poa', 'Missing ID / POA', 'danger', 'mdi-card-account-details-outline', 'Clients waiting on documents', false, 'down'),
            $card($metrics->currentlyInStatus(DashboardMetrics::STATUS_SENT_TO_REDRESS), 'waiting_on_app_number', 'Waiting on APP Number', 'warning', 'mdi-timer-sand', '', false, 'down'),
            $card($metrics->currentlyInStatus(DashboardMetrics::STATUS_INVESTIGATION), 'investigation_dsar_activity', 'Investigation - DSAR Activity', 'info', 'mdi-magnify', '', false, 'neutral'),
            $card($metrics->activelyClaiming(), 'actively_claiming', 'Actively Claiming', 'success', 'mdi-account-group', 'Open clients in the active pipeline', false, 'up'),
            $card($metrics->institutionsCount(), 'institutions', 'Individual Care Settings', 'dark', 'mdi-office-building', 'Number of institutions in the system', true, 'neutral'),
            $card($metrics->emailsOutstanding(), 'emails_outstanding', 'Emails Outstanding', 'danger', 'mdi-email-alert', 'Inbound emails still needing action', true, 'down'),
        ];

        $sections = [
            [
                'title' => 'Acquisition & Contact', 'icon' => 'mdi-account-plus', 'accent' => 'primary',
                'rows'  => [
                    $throughput(fn ($f, $t) => $metrics->leadsCreated($f, $t), 'Leads In', '(created)', 'How well lead gen is performing'),
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_WELCOME_CALL, $f, $t), 'Client Contacted'),
                    $derived(fn ($f, $t) => $metrics->contactRate($f, $t), 'percent', 'Contact Rate', 'Our contact rate'),
                ],
            ],
            [
                'title' => 'Contracts', 'icon' => 'mdi-file-sign', 'accent' => 'info',
                'rows'  => [
                    $throughput(fn ($f, $t) => $metrics->contractsSent($f, $t), 'Contracts Sent'),
                    $throughput(fn ($f, $t) => $metrics->contractsSigned($f, $t), 'Contracts Signed'),
                    $derived(fn ($f, $t) => $metrics->signUpRate($f, $t), 'percent', 'Sign up rate', 'Sign up rate'),
                ],
            ],
            [
                'title' => 'Redress & APP', 'icon' => 'mdi-bank-transfer', 'accent' => 'warning',
                'rows'  => [
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_SENT_TO_REDRESS, $f, $t), 'Sent To Redress', '(Parts 1/3)'),
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_APP_NUMBER, $f, $t), 'APP Number Received'),
                    $derived(fn ($f, $t) => $metrics->avgAppLeadTime($f, $t), 'days', 'Average APP Number Lead Time', 'How long redress take to return APP numbers'),
                ],
            ],
            [
                'title' => 'Investigation & DSAR', 'icon' => 'mdi-magnify', 'accent' => 'secondary',
                'rows'  => [
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_INVESTIGATION, $f, $t), 'Ready For DSAR'),
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_DSARS_SENT, $f, $t), 'DSAR Sent'),
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_PART_DSAR, $f, $t), 'Part Dsar Received'),
                ],
            ],
            [
                'title' => 'Closed', 'icon' => 'mdi-check-circle', 'accent' => 'success',
                'rows'  => [
                    $throughput(fn ($f, $t) => $metrics->changedToStatus(DashboardMetrics::STATUS_CLOSED, $f, $t), 'Closed'),
                    $throughput(fn ($f, $t) => $metrics->closedWithTag(DashboardMetrics::TAG_CLOSED_ANOTHER_FIRM, $f, $t), 'Closed', '— with another firm'),
                    $throughput(fn ($f, $t) => $metrics->closedWithTag(DashboardMetrics::TAG_CLOSED_NO_CONTACT, $f, $t), 'Closed', '— no contact'),
                    $throughput(fn ($f, $t) => $metrics->closedWithTag(DashboardMetrics::TAG_CLOSED_NO_CRITERIA, $f, $t), 'Closed', '— does not meet criteria'),
                    $throughput(fn ($f, $t) => $metrics->closedWithTag(DashboardMetrics::TAG_CLOSED_DUPLICATE, $f, $t), 'Closed', '— duplicate'),
                ],
            ],
        ];

        return view('components.report.pipeline-kpis', [
            'currentCards' => $currentCards,
            'sections'     => $sections,
            'leadSources'  => LeadSource::where('status', 'active')->orderBy('display_name')->get(['id', 'display_name']),
            'showDeltas'   => $showDeltas,
        ]);
    }
}
