<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
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\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\MultiSelect;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;
use Filament\Facades\Filament;
use Illuminate\Database\Eloquent\Model;



class UserResource extends Resource
{
    // protected static ?string $navigationLabel = 'Usuarios';
   protected static ?string $navigationIcon = 'heroicon-o-users'; // ícono opcional
    protected static ?int $navigationSort = 1;


    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                ->label('Nombre Completo')
                ->required()
                ->dehydrateStateUsing(function ($state) {
                        return ucwords(strtolower($state));
                    }),
                Forms\Components\TextInput::make('ci')
                    ->label('CI')
                    ->unique(ignoreRecord: true)
                    ->required()
                    ->validationMessages([
                        'unique' => 'Este número de CI ya está registrado.',
                ]),
                Forms\Components\TextInput::make('email')
                ->label('Correo')
                ->email()
                ->required()
                ->unique(ignoreRecord: true)
                ->validationMessages([
                    'unique' => 'Este correo ya está registrado.',
                ]),

                Forms\Components\TextInput::make('password')
                ->password()
                ->required(fn ($livewire) => $livewire instanceof \App\Filament\Resources\UserResource\Pages\CreateUser)
                ->dehydrated(fn ($state) => filled($state))
                ->label('Contraseña')
                ->afterStateHydrated(function ($component, $state) {
                    $component->state('');
                })
                ->dehydrateStateUsing(fn ($state) => Hash::make($state)),
                 Forms\Components\Select::make('roles')
                ->label('Rol')
                ->preload()
                ->relationship('roles', 'name')
                ->required(),

                Forms\Components\Toggle::make('status')
                    ->label('Activo')
                    ->default(true),

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
               Tables\Columns\TextColumn::make('name')->label('Nombre Completo')->searchable(),
            Tables\Columns\TextColumn::make('ci')->searchable(),
            Tables\Columns\TextColumn::make('email')->searchable(),
            Tables\Columns\IconColumn::make('status')
                ->label('Estado')
                ->boolean()
                ->trueIcon('heroicon-o-check-circle')
                ->falseIcon('heroicon-o-x-circle'),
            Tables\Columns\TextColumn::make('roles.name')->label('Rol')->badge(),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make()
                    ->visible(fn () => auth()->user()?->can('usuario.update')),

                Tables\Actions\Action::make('inactivar')
                    ->label('Eliminar')
                    ->icon('heroicon-o-trash')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->visible(fn () => auth()->user()?->can('usuario.delete'))
                    ->action(function (User $record) {
                        $record->status = 0;
                        $record->save();
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }



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

    public static function getNavigationGroup(): ?string
    {
        return 'Gestionar usuarios';
    }

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

    public static function getPluralModelLabel(): string
    {
        return 'Usuarios';
    }

    // public static function getEloquentQuery(): Builder
    // {
    //     return parent::getEloquentQuery()
    //         ->where('id', '<>', 1)
    //         ->where('status', 1)
    //         ->whereDoesntHave('roles', function ($query) {
    //             $query->whereIn('name', ['', 'gerente']);

    //         });
    // }


    public static function canViewAny(): bool
    {
        return auth()->user()?->can('usuario.view');
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('usuario.create');
    }

    public static function canEdit(Model $record): bool
    {
        return auth()->user()?->can('usuario.update');
    }

    public static function canDelete(Model $record): bool
    {
        return auth()->user()?->can('usuario.delete');
    }



}
