<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ClasaResource\Pages;
use App\Filament\Resources\ClasaResource\RelationManagers;
use App\Models\Clasa;
use App\Models\Scoala;
use App\Models\User;
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\Support\Facades\Auth;

class ClasaResource extends Resource
{
    protected static ?string $model = Clasa::class;
    protected static ?string $navigationIcon = 'heroicon-o-academic-cap';
    protected static ?string $navigationLabel = 'Clase';
    protected static ?string $pluralModelLabel = 'Clase';
    protected static ?string $modelLabel = 'Clasă';

    public static function form(Form $form): Form
    {
        $user = Auth::user();
        $isAdmin = $user?->hasRole('admin');
        $canEdit = $user?->hasAnyRole(['admin', 'director', 'secretariat']);

        return $form
            ->schema([
                Forms\Components\Select::make('scoala_id')
                    ->label('Școala')
                    ->options(Scoala::all()->pluck('nume', 'id'))
                    ->required()
                    ->searchable()
                    ->visible($isAdmin)
                    ->default($user?->scoala_id),
                Forms\Components\TextInput::make('nume')
                    ->label('Clasa (ex: 9A, 10B)')
                    ->required(),
                Forms\Components\TextInput::make('an_scolar')
                    ->label('An școlar (ex: 2024)')
                    ->numeric()
                    ->required(),
                Forms\Components\Select::make('tip_perioada')
                    ->label('Tip perioadă')
                    ->options([
                        'semestre' => 'Semestre',
                        'trimestre' => 'Trimestre',
                        'module' => 'Module',
                    ])
                    ->required(),
                Forms\Components\Select::make('diriginte_user_id')
                    ->label('Diriginte')
                    ->options(fn() => User::role(['profesor', 'diriginte'])->pluck('name', 'id'))
                    ->searchable()
                    ->nullable()
                    ->visible($canEdit),
                Forms\Components\Toggle::make('cu_teze')
                    ->label('Se dau teze')
                    ->helperText('Teza contează 25% din media semestrială (ROFUIP)')
                    ->default(false)
                    ->visible($canEdit),
                Forms\Components\Section::make('Notificări')
                    ->description('Lasă nesetat pentru a moșteni setarea de la școală')
                    ->schema([
                        Forms\Components\Select::make('notificari_email')
                            ->label('Notificări email')
                            ->options(['' => 'Moștenește de la școală', '1' => 'Activat', '0' => 'Dezactivat'])
                            ->default(null),
                        Forms\Components\Select::make('notificari_whatsapp')
                            ->label('Notificări WhatsApp')
                            ->options(['' => 'Moștenește de la școală', '1' => 'Activat', '0' => 'Dezactivat'])
                            ->default(null),
                    ])->columns(2)
                    ->visible($canEdit),
            ]);
    }

    public static function table(Table $table): Table
    {
        $isAdmin = Auth::user()?->hasRole('admin');
        $canEdit = Auth::user()?->hasAnyRole(['admin', 'director', 'secretariat']);

        return $table
            ->columns([
                Tables\Columns\TextColumn::make('scoala.nume')
                    ->label('Școala')
                    ->searchable()
                    ->visible($isAdmin),
                Tables\Columns\TextColumn::make('nume')
                    ->label('Clasa')
                    ->searchable(),
                Tables\Columns\TextColumn::make('an_scolar')
                    ->label('An școlar')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tip_perioada')
                    ->label('Tip perioadă'),
                Tables\Columns\TextColumn::make('diriginte.name')
                    ->label('Diriginte')
                    ->placeholder('—'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make()
                    ->visible($canEdit),
                Tables\Actions\DeleteAction::make()
                    ->visible(fn() => Auth::user()?->hasAnyRole(['admin', 'director'])),
            ])
            ->bulkActions([]);
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();
        $user = Auth::user();

        if ($user?->hasRole('diriginte') && !$user?->hasRole('profesor')) {
            $query->where('diriginte_user_id', $user->id);
        } elseif ($user?->hasRole('profesor')) {
            $clasaIds = $user->materii()->pluck('clasa_id');
            if ($user?->hasRole('diriginte')) {
                $query->where(function (Builder $q) use ($user, $clasaIds) {
                    $q->whereIn('clase.id', $clasaIds)
                      ->orWhere('diriginte_user_id', $user->id);
                });
            } else {
                $query->whereIn('clase.id', $clasaIds);
            }
        }

        return $query;
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\PerioadeRelationManager::class,
            RelationManagers\EleviRelationManager::class,
            RelationManagers\MateriiRelationManager::class,
            RelationManagers\OrarRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListClasas::route('/'),
            'create' => Pages\CreateClasa::route('/create'),
            'view' => Pages\ViewClasa::route('/{record}'),
            'edit' => Pages\EditClasa::route('/{record}/edit'),
            'import-elevi' => Pages\ImportElevi::route('/import-elevi'),
            'edit-orar' => Pages\EditOrar::route('/{record}/edit-orar'),
        ];
    }
}
