<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SesiResource\Pages;
use App\Filament\Resources\SesiResource\RelationManagers;
use App\Models\Sesi;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DatePicker;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Model;

class SesiResource extends Resource
{
    protected static ?string $model = Sesi::class;

    protected static ?string $navigationIcon = 'heroicon-c-information-circle';

    protected static ?string $navigationLabel = 'SESI';

    protected static ?string $pluralModelLabel = 'SESI';

    protected static ?string $navigationGroup = 'UTILITI';

    protected static ?string $slug = 'sesi';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                DatePicker::make('sesi_mula')
                    ->native(false)
                    ->label('Sesi Mula')
                    ->rules('required')
                    ->displayFormat('Y')
                    ->format('Y')
                    ->live()
                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                        self::updateNama($get, $set);
                    }),
                DatePicker::make('sesi_tamat')
                    ->native(false)
                    ->label('Sesi Tamat')
                    ->rules('required')
                    ->displayFormat('Y')
                    ->format('Y')
                    ->live()
                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                        self::updateNama($get, $set);
                    }),
                Forms\Components\TextInput::make('semester')
                    ->label('Semester')
                    ->integer()
                    ->rules('required')
                    ->live()
                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                        self::updateNama($get, $set);
                    }),
                Forms\Components\TextInput::make('nama')
                    ->label('Nama')
                    // ->disabled()
                    ->extraInputAttributes(['readonly' => true])
                    ->rules('required'),
                Select::make('aktif')
                    ->placeholder('Sila Pilih Maklumat')
                    ->options([
                        '1' => 'AKTIF',
                        '0' => 'TIDAK AKTIF',
                    ])
                    ->rules('required'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('index')->label('NO')->rowIndex(),
                Tables\Columns\TextColumn::make('nama'),
                IconColumn::make('aktif')
                    ->label('Status')
                    ->boolean(),
                TextColumn::make('nama')->searchable(),
            ])
            ->deferLoading()
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make()->label(''),
                Tables\Actions\DeleteAction::make()
                    ->label('')
                    ->visible(function (Sesi $record) {
                        // Check if the record has related tugas entries
                        return $record->tugas()->count() === 0;
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    //Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSesis::route('/'),
            'create' => Pages\CreateSesi::route('/create'),
            'edit' => Pages\EditSesi::route('/{record:slug}/edit'),
        ];
    }

    protected static function updateNama(callable $get, callable $set)
    {

        if (empty($get('sesi_mula'))) {
            $sesiMula = "";
        } else {
            $sesiMula = date("Y", strtotime($get('sesi_mula')));
        }

        if (empty($get('sesi_tamat'))) {
            $sesiTamat = "";
        } else {
            $sesiTamat = date("Y", strtotime($get('sesi_tamat')));
        }

        if (empty($get('semester'))) {
            $semester = "";
        } else {
            $semester = $get('semester');
        }

        // $sesiMula = date("Y", strtotime($get('sesi_mula')));
        // $sesiTamat = date("Y", strtotime($get('sesi_tamat')));
        // $semester = $get('semester');

        $nama = trim("{$semester} {$sesiMula} / {$sesiTamat}");
        $set('nama', $nama);
    }

    public static function canViewAny(): bool
    {
        // dd(auth()->user()->roles());
        return auth()
            ->user()
            ->hasAnyRole(['Super Admin']);
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }

    public static function canDelete(Model $record): bool
    {
        return ! $record->tugas()->exists();
    }
}
