<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
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\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

class UserResource extends Resource
{
    protected static ?string $model = User::class;
    protected static ?string $navigationIcon = 'heroicon-o-users';
    protected static ?string $navigationLabel = 'Utilizatori';
    protected static ?string $pluralModelLabel = 'Utilizatori';
    protected static ?string $modelLabel = 'Utilizator';
    protected static ?int $navigationSort = 100;

    public static function canAccess(): bool
    {
        return auth()->user()?->hasAnyRole(['admin', 'director']) ?? false;
    }

    public static function form(Form $form): Form
    {
        $user = Auth::user();
        $isAdmin = $user?->hasRole('admin');

        return $form
            ->schema([
                Forms\Components\Section::make('Date cont')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('Nume complet')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('email')
                            ->label('Email')
                            ->email()
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(255),
                        Forms\Components\TextInput::make('password')
                            ->label('Parolă')
                            ->password()
                            ->dehydrateStateUsing(fn($state) => filled($state) ? Hash::make($state) : null)
                            ->dehydrated(fn($state) => filled($state))
                            ->required(fn(string $operation) => $operation === 'create')
                            ->maxLength(255)
                            ->helperText(fn(string $operation) => $operation === 'edit' ? 'Lasă gol pentru a păstra parola actuală' : null),
                    ])->columns(2),

                Forms\Components\Section::make('Rol și școală')
                    ->schema([
                        Forms\Components\Select::make('roles')
                            ->label('Rol')
                            ->relationship('roles', 'name')
                            ->options(function () use ($isAdmin) {
                                $query = Role::query();
                                if (!$isAdmin) {
                                    $query->whereNotIn('name', ['admin']);
                                }
                                return $query->pluck('name', 'id');
                            })
                            ->multiple()
                            ->preload()
                            ->required(),
                        Forms\Components\Select::make('scoala_id')
                            ->label('Școala')
                            ->options(fn() => Scoala::pluck('nume', 'id'))
                            ->searchable()
                            ->nullable()
                            ->visible($isAdmin)
                            ->default($user?->scoala_id)
                            ->helperText('Admin-ul nu necesită școală. Toți ceilalți trebuie asociați unei școli.'),
                    ])->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        $isAdmin = Auth::user()?->hasRole('admin');

        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nume')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('email')
                    ->label('Email')
                    ->searchable(),
                Tables\Columns\TextColumn::make('roles.name')
                    ->label('Rol')
                    ->badge()
                    ->colors([
                        'danger' => 'admin',
                        'warning' => 'director',
                        'info' => 'secretariat',
                        'success' => 'diriginte',
                        'primary' => 'profesor',
                        'gray' => fn($state) => in_array($state, ['parinte', 'elev']),
                    ]),
                Tables\Columns\TextColumn::make('scoala.nume')
                    ->label('Școala')
                    ->placeholder('—')
                    ->visible($isAdmin),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Creat la')
                    ->dateTime('d.m.Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('roles')
                    ->label('Rol')
                    ->relationship('roles', 'name'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make()
                    ->visible(fn($record) => $record->id !== Auth::id()),
            ])
            ->bulkActions([]);
    }

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

        if ($user?->hasRole('director') && !$user?->hasRole('admin')) {
            $query->where('scoala_id', $user->scoala_id);
        }

        return $query;
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUsers::route('/'),
            'create' => Pages\CreateUser::route('/create'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }
}
