<?php

namespace App\Filament\Siswa\Resources;

use App\Filament\Siswa\Resources\RekapanSiswaResource\Pages\CreateRekapanSiswa;
use App\Filament\Siswa\Resources\RekapanSiswaResource\Pages\EditRekapanSiswa;
use App\Filament\Siswa\Resources\RekapanSiswaResource\Pages\ListRekapanSiswas;
use App\Models\Guru;
use App\Models\Jadwal;
use App\Models\Kelas;
use App\Models\Mapel;
use App\Models\RekapanSiswa;
use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class RekapanSiswaResource extends Resource
{
    protected static ?string $model = RekapanSiswa::class;

    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-check';

    protected static ?string $modelLabel = 'Rekap Pengajar';
    protected static ?string $navigationLabel = 'Rekap pengajar';
    protected static ?string $pluralModelLabel = 'Rekap pengajar';

    protected static ?string $slug = 'rekap-pengajar';

    public static function form(Form $form): Form
    {
        $kelasSiswa = Auth::user()->siswa->kelas_id;

        return $form
            ->schema([
                Hidden::make('siswa_id')
                    ->default(function () {
                        return Auth::user()->id;
                    }),
                Hidden::make('kelas_id')
                    ->default(function () {
                        return Auth::user()->siswa->kelas_id;
                    }),
                Select::make('kelas_id_display')
                    ->label('Kelas')
                    ->options(function () {
                        $kelasSiswa = Auth::user()->siswa->kelas_id;
                        return Kelas::where('id', $kelasSiswa)
                            ->pluck('nama_kelas', 'id');
                    })
                    ->default(Auth::user()->siswa->kelas_id)
                    ->disabled()
                    ->dehydrated(false),
                Select::make('guru_id')
                    ->label('Guru')
                    ->options(Guru::all()->pluck('nama', 'id'))
                    ->searchable(),
                Select::make('mapel_id')
                    ->label('Mata Pelajaran')
                    ->options(Mapel::all()->pluck('nama_mapel', 'id'))
                    ->required()
                    ->searchable(),
                Select::make('jadwal_id')
                    ->label('Jadwal Mengajar')
                    ->prefixIcon('heroicon-o-clock')
                    ->options(Jadwal::all()->map(function ($jadwal) {
                        return [
                            'id' => $jadwal->id,
                            'label' => ucfirst($jadwal->hari) . ' | Jam ke-' . $jadwal->jam_ke . 
                                    ' (' . Carbon::parse($jadwal->waktu_mulai)->format('H:i') . ' - ' . 
                                    Carbon::parse($jadwal->waktu_selesai)->format('H:i') . ')'
                        ];
                    })->pluck('label', 'id'))
                    ->required()
                    ->searchable(),
                DatePicker::make('tanggal')
                    ->required()
                    ->default(now()),
                Select::make('status')
                    ->options([
                        'hadir_mengajar' => 'Hadir Mengajar',
                        'tidak_mengajar' => 'Tidak Mengajar',
                        'hadir_digantikan' => 'Hadir Digantikan',
                    ])
                    ->searchable()
                    ->required()
                    ->default('hadir_mengajar'),
                Textarea::make('keterangan')
                    ->label('Keterangan')
                    ->placeholder('Contoh: Guru digantikan oleh Bu Ani karena sakit')
                    ->nullable()
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('tanggal')
                    ->date()
                    ->sortable(),
                TextColumn::make('kelas.nama_kelas')
                    ->label('Kelas'),
                TextColumn::make('guru.user.name')
                    ->label('Guru'),
                TextColumn::make('mapel.nama_mapel')
                    ->label('Mapel'),
                TextColumn::make('jadwal.hari')
                    ->label('Hari')
                    ->formatStateUsing(fn (string $state): string => ucfirst($state)),
                TextColumn::make('jadwal.jam_ke')
                    ->label('Jam Ke')
                    ->formatStateUsing(fn ($state) => "Jam ke-$state"),
                TextColumn::make('waktu')
                    ->label('Waktu')
                    ->getStateUsing(function ($record) {
                        if ($record->jadwal && $record->jadwal->waktu_mulai && $record->jadwal->waktu_selesai) {
                            return $record->jadwal->waktu_mulai->format('H:i') . ' - ' . 
                                $record->jadwal->waktu_selesai->format('H:i');
                        }
                        return 'Waktu tidak tersedia';
                    }),
                TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'hadir_mengajar' => 'Hadir Mengajar',
                        'tidak_mengajar' => 'Tidak Mengajar',
                        'hadir_digantikan' => 'Hadir Digantikan',
                        default => ucfirst(str_replace('_', ' ', $state)),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'hadir_mengajar' => 'success',
                        'tidak_mengajar' => 'danger',
                        'hadir_digantikan' => 'warning',
                    }),
            ])
            ->modifyQueryUsing(function (Builder $query) {
                $kelasSiswa = Auth::user()->siswa->kelas_id ?? null;
                
                $query->where(function($q) use ($kelasSiswa) {
                    $q->whereHas('kelas', function($q) use ($kelasSiswa) {
                        $q->where('id', $kelasSiswa);
                    });
                    
                    $q->orWhere('siswa_id', Auth::id());
                });
            })
            ->filters([
                SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'hadir_mengajar' => 'Hadir Mengajar',
                        'tidak_mengajar' => 'Tidak Mengajar', 
                        'hadir_digantikan' => 'Hadir Digantikan',
                    ])
                    ->multiple(),
            ])
            ->filtersLayout(FiltersLayout::Modal)
            ->filtersFormColumns(1)
            ->actions([
                // EditAction::make()
            ])
            ->bulkActions([
                // DeleteBulkAction::make(),
            ]);
    }

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

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