<?php

namespace App\Filament\Widgets;

use App\Models\User;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;

class UserGrowthChart extends ChartWidget
{
    use InteractsWithPageFilters;
    public function getHeading(): string
    {
        return __('User Growth Over Time');
    }

    protected int | string | array $columnSpan = [
        'md' => '50%',
        'xl' => '50%',
    ];

    protected function getFilters(): ?array
    {
        return [];
    }

    protected function getData(): array
    {
        $dateFrom = $this->filters['date_from'] ?? null;
        $dateUntil = $this->filters['date_until'] ?? null;

        $query = User::query();

        if ($dateFrom) {
            $query->whereDate('created_at', '>=', Carbon::parse($dateFrom));
        }

        if ($dateUntil) {
            $query->whereDate('created_at', '<=', Carbon::parse($dateUntil));
        }

        $dateRange = $query->clone()
            ->selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, COUNT(*) as count')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        $labels = $dateRange->pluck('month')->toArray();
        $data = $dateRange->pluck('count')->toArray();

        return [
            'datasets' => [
                [
                    'label' => __('New Users'),
                    'data' => $data,
                    'borderColor' => '#3B82F6',
                    'backgroundColor' => '#3B82F6',
                    'fill' => true,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'line';
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => true,
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                ],
            ],
        ];
    }
}
