<?php

namespace App\Filament\Pages;

use App\Enums\RoleEnum;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Pages\Dashboard as BaseDashboard;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;

class Dashboard extends BaseDashboard
{
    use HasFiltersForm, HasPageShield;

    public function getColumns(): int|array
    {
        return 2;
    }

    public function filtersForm(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Fieldset::make('Filter')
                    ->schema([
                        DatePicker::make('startDate')
                            ->label('Tanggal Mulai')
                            ->placeholder('Pilih tanggal mulai')
                            ->native(false)
                            ->displayFormat('l, d F Y'),

                        DatePicker::make('endDate')
                            ->label('Tanggal Selesai')
                            ->placeholder('Pilih tanggal selesai')
                            ->native(false)
                            ->displayFormat('l, d F Y'),
                    ])
                    ->columns(2)
                    ->columnSpanFull()
                    ->visible(fn () => auth()->user()->hasRole(RoleEnum::DEVELOPER->value) || auth()->user()->hasRole(RoleEnum::ADMINISTRATOR->value)),
            ]);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('reset')
                ->label('Reset Filter')
                ->icon(Heroicon::XMark)
                ->color('danger')
                ->action(fn () => $this->resetFilters())
                ->visible(fn () => ! empty($this->filters['startDate']) || ! empty($this->filters['endDate'])),
        ];
    }

    public function resetFilters(): void
    {
        $this->filters['startDate'] = null;
        $this->filters['endDate'] = null;

        if (method_exists($this, 'getFiltersSessionKey')) {
            session()->forget($this->getFiltersSessionKey());
        }
    }
}
