<?php

namespace App\Filament\Widgets;

use App\Models\AssessmentAttempt;
use App\Models\Consultation;
use App\Models\Enrollment;
use App\Models\Lead;
use App\Models\ToolResult;
use App\Models\User;
use Filament\Widgets\Widget;
use Illuminate\Support\Str;

class RecentActivity extends Widget
{
    protected string $view = 'filament.widgets.recent-activity';

    protected int|string|array $columnSpan = 'full';

    protected static ?int $sort = 0;

    protected static bool $isLazy = false;

    public function getViewData(): array
    {
        $items = collect();

        foreach (User::latest()->limit(8)->get() as $u) {
            $items->push(['type' => 'signup', 'title' => 'New member joined', 'meta' => $u->name, 'at' => $u->created_at]);
        }

        foreach (AssessmentAttempt::with('assessment')->where('status', 'completed')->latest('completed_at')->limit(8)->get() as $a) {
            $items->push([
                'type' => 'assessment',
                'title' => 'Completed '.($a->assessment->title ?? 'an assessment'),
                'meta' => ($a->guest_name ?: optional($a->user)->name ?: 'Guest').' · '.round((float) $a->percent).'%',
                'at' => $a->completed_at,
            ]);
        }

        foreach (Consultation::latest()->limit(8)->get() as $c) {
            $items->push(['type' => 'consultation', 'title' => 'Booked a consultation', 'meta' => $c->name.' · '.Str::headline((string) $c->topic), 'at' => $c->created_at]);
        }

        foreach (Lead::latest()->limit(8)->get() as $l) {
            $items->push(['type' => 'lead', 'title' => 'New lead captured', 'meta' => ($l->name ?: $l->email).' · '.Str::headline((string) $l->source), 'at' => $l->created_at]);
        }

        foreach (Enrollment::with(['user', 'course'])->latest()->limit(8)->get() as $e) {
            $items->push(['type' => 'enrollment', 'title' => 'Enrolled in '.($e->course->title ?? 'a course'), 'meta' => optional($e->user)->name ?? 'Member', 'at' => $e->created_at]);
        }

        foreach (ToolResult::with('user')->latest()->limit(8)->get() as $t) {
            $items->push(['type' => 'tool', 'title' => 'Used the '.Str::headline((string) $t->tool).' tool', 'meta' => optional($t->user)->name ?? 'Guest', 'at' => $t->created_at]);
        }

        return [
            'activity' => $items->filter(fn ($i) => $i['at'])->sortByDesc('at')->take(12)->values(),
        ];
    }
}
