<?php

namespace App\Filament\Resources;

use App\Enums\UserRole;
use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Actions\DeleteAction;

class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static ?string $navigationIcon   = 'heroicon-o-user-group';
    protected static ?string $navigationGroup  = 'Configuración';
    protected static ?string $navigationLabel  = 'Usuarios';
    protected static ?string $modelLabel       = 'Usuario';
    protected static ?string $pluralModelLabel = 'Usuarios';
    protected static ?int    $navigationSort   = 0;

    // ── Permisos: solo admin_sistema ─────────────────────────────────────────

    public static function canViewAny(): bool
    {
        return auth()->user()?->isAdmin() ?? false;
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->isAdmin() ?? false;
    }

    public static function canEdit($record): bool
    {
        return auth()->user()?->isAdmin() ?? false;
    }

    public static function canDelete($record): bool
    {
        // No puede borrar su propia cuenta
        if ($record->id === auth()->id()) {
            return false;
        }
        return auth()->user()?->isAdmin() ?? false;
    }

    // ── Formulario ───────────────────────────────────────────────────────────

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Datos del usuario')
                ->columns(2)
                ->schema([
                    Forms\Components\TextInput::make('name')
                        ->label('Nombre')
                        ->required()
                        ->maxLength(255)
                        ->columnSpan(1),

                    Forms\Components\TextInput::make('email')
                        ->label('Correo electrónico')
                        ->email()
                        ->required()
                        ->unique(table: User::class, column: 'email', ignoreRecord: true)
                        ->maxLength(255)
                        ->columnSpan(1),

                    Forms\Components\Select::make('role')
                        ->label('Rol')
                        ->options(
                            collect(UserRole::cases())
                                ->mapWithKeys(fn (UserRole $r) => [$r->value => $r->label()])
                        )
                        ->required()
                        ->columnSpan(1),

                    Forms\Components\TextInput::make('password')
                        ->label(fn (string $operation): string => $operation === 'create'
                            ? 'Contraseña'
                            : 'Nueva contraseña (vacío = no cambiar)')
                        ->password()
                        ->required(fn (string $operation): bool => $operation === 'create')
                        ->dehydrated(fn (?string $state): bool => filled($state))
                        ->dehydrateStateUsing(fn (string $state): string => bcrypt($state))
                        ->minLength(8)
                        ->columnSpan(1),
                ]),
        ]);
    }

    // ── Tabla ─────────────────────────────────────────────────────────────────

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label('Nombre')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('email')
                    ->label('Email')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('role')
                    ->label('Rol')
                    ->badge()
                    ->color(fn (UserRole $state): string => match ($state) {
                        UserRole::AdminSistema  => 'danger',
                        UserRole::ContadorAdmin => 'warning',
                        UserRole::GestorCuenta  => 'success',
                        UserRole::Vendedor      => 'info',
                    })
                    ->formatStateUsing(fn (UserRole $state): string => $state->label())
                    ->sortable(),

                TextColumn::make('created_at')
                    ->label('Creado')
                    ->dateTime('d/m/Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('role')
                    ->label('Rol')
                    ->options(
                        collect(UserRole::cases())
                            ->mapWithKeys(fn (UserRole $r) => [$r->value => $r->label()])
                    ),
            ])
            ->actions([
                EditAction::make(),
                DeleteAction::make()
                    ->disabled(fn (User $record): bool => $record->id === auth()->id()),
            ])
            ->defaultSort('name', 'asc');
    }

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