<?php

namespace App\Filament\Resources;

use App\Filament\Resources\MapelResource\Pages\CreateMapel;
use App\Filament\Resources\MapelResource\Pages\EditMapel;
use App\Filament\Resources\MapelResource\Pages\ListMapels;
use App\Filament\Resources\MapelResource\RelationManagers\JadwalsRelationManager;
use App\Models\Mapel;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Set;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables\Actions\BulkActionGroup;
use Filament\Tables\Actions\CreateAction;
use Filament\Tables\Actions\DeleteAction;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class MapelResource extends Resource
{
    protected static ?string $model = Mapel::class;

    // protected static ?string $navigationIcon = 'heroicon-o-book-open';

    protected static ?string $navigationGroup = 'Master Data';
    protected static ?int $navigationSort = 1;

    protected static ?string $modelLabel = 'Mapel';
    protected static ?string $navigationLabel  = 'Manajemen Mapel';
    protected static ?string $pluralModelLabel = 'Daftar Mapel';

    protected static ?string $slug = 'mapel';

    protected static ?string $navigationBadgeTooltip = 'Mapel baru hari ini';

    public static function getNavigationBadge(): ?string
    {
        $count = static::getModel()::whereDate('created_at', today())->count();
        return $count > 0 ? (string) $count : null;
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return static::getModel()::whereDate('created_at', today())->exists() ? 'success' : null;
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                TextInput::make('kode_mapel')
                    ->label('Kode Mapel')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-code-bracket')
                    ->required()
                    ->maxLength(10)
                    ->unique(ignoreRecord: true)
                    ->suffixAction(
                        Action::make('generateCode')
                            ->icon('heroicon-m-arrow-path')
                            ->action(function (Set $set) {
                                $set('kode_mapel', self::generateRandomMapelCode());
                            })
                    ),
                TextInput::make('nama_mapel')
                    ->label('Nama Mapel')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-book-open')
                    ->required()
                    ->maxLength(100),
                Textarea::make('deskripsi')
                    ->label('Deskripsi')
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('kode_mapel')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('nama_mapel')
                    ->searchable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make(),
                DeleteAction::make()
                    ->successNotification(null)
                    ->after(function ($record) {
                        Notification::make()
                            ->title('Data Mapel Dihapus')
                            ->success()
                            ->body("Data mapel {$record->nama_mapel} berhasil dihapus")
                            ->sendToDatabase(Auth::user());
                    }),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->label('Hapus Data Terpilih')
                        ->successNotification(null)
                        ->after(function ($records) {
                            $count = $records->count();

                            Notification::make()
                                ->title('Data Mapel Dihapus')
                                ->success()
                                ->body("{$count} mapel berhasil dihapus")
                                ->sendToDatabase(Auth::user());
                        }),
                ]),
            ])
            ->emptyStateHeading('Belum ada data mapel')
            ->emptyStateDescription('Klik tombol dibawah untuk membuat mapel baru')
            ->emptyStateActions([
                CreateAction::make()
                    ->label('Buat Mapel')
                    ->icon('heroicon-o-plus'),
            ])
            ->deferLoading();
    }

    private static function generateRandomMapelCode(): string
    {
        $prefix = 'MPL-';
        $random = strtoupper(substr(md5(uniqid()), 0, 4));
        return $prefix . $random;
    }

    public static function getRelations(): array
    {
        return [
            JadwalsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListMapels::route('/'),
            'create' => CreateMapel::route('/create'),
            'edit' => EditMapel::route('/{record}/edit'),
        ];
    }
}
