<?php

namespace App\Filament\Resources;

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;

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

    protected static ?string $navigationIcon = 'heroicon-o-users';

    protected static ?string $navigationLabel = 'Usuarios';

    protected static ?string $modelLabel = 'Usuario';

    protected static ?string $pluralModelLabel = 'Usuarios';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Información Personal')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('Nombre Completo')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\TextInput::make('email')
                            ->label('Correo Electrónico')
                            ->email()
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(255),

                        Forms\Components\TextInput::make('cedula')
                            ->label('Cédula / Identificación')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(30),

                        Forms\Components\TextInput::make('phone')
                            ->label('Teléfono')
                            ->tel()
                            ->maxLength(50),

                        Forms\Components\TextInput::make('password')
                            ->label('Contraseña')
                            ->password()
                            ->dehydrated(fn ($state) => filled($state))
                            ->required(fn (string $context): bool => $context === 'create')
                            ->maxLength(255),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Rol, Estado y Lealtad')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Select::make('role_id')
                                    ->label('Rol del Usuario')
                                    ->relationship('role', 'display_name')
                                    ->required()
                                    ->placeholder('Seleccione un rol'),

                                Forms\Components\Select::make('status')
                                    ->label('Estado de la Cuenta')
                                    ->options([
                                        'active' => 'Activo',
                                        'suspended' => 'Suspendido',
                                    ])
                                    ->required()
                                    ->default('active'),

                                Forms\Components\Select::make('vip_level_id')
                                    ->label('Nivel VIP')
                                    ->relationship('vipLevel', 'display_name')
                                    ->placeholder('Ninguno'),
                            ]),
                    ]),

                Forms\Components\Section::make('Saldos y Red de Afiliados')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\TextInput::make('wallet_balance')
                                    ->label('Saldo de Wallet')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->required()
                                    ->default(0.00),

                                Forms\Components\TextInput::make('points_balance')
                                    ->label('Saldo de Puntos')
                                    ->numeric()
                                    ->required()
                                    ->default(0),

                                Forms\Components\Select::make('referred_by_id')
                                    ->label('Patrocinador (Referido por)')
                                    ->relationship('referredBy', 'name')
                                    ->searchable()
                                    ->placeholder('Ninguno'),
                            ]),
                    ]),
            ]);
    }

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

                Tables\Columns\TextColumn::make('email')
                    ->label('Correo')
                    ->searchable(),

                Tables\Columns\TextColumn::make('cedula')
                    ->label('Cédula')
                    ->searchable(),

                Tables\Columns\TextColumn::make('phone')
                    ->label('Teléfono')
                    ->searchable(),

                Tables\Columns\TextColumn::make('role.display_name')
                    ->label('Rol')
                    ->badge()
                    ->color(fn ($record): string => match ($record?->role?->name) {
                        'admin' => 'danger',
                        'reseller' => 'warning',
                        default => 'info',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('vipLevel.display_name')
                    ->label('VIP')
                    ->badge()
                    ->color(fn ($record): string => match ($record?->vipLevel?->name) {
                        'bronce' => 'amber',
                        'plata' => 'slate',
                        'oro' => 'yellow',
                        default => 'gray',
                    })
                    ->default('Ninguno')
                    ->sortable(),

                Tables\Columns\TextColumn::make('wallet_balance')
                    ->label('Saldo Wallet')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('₡')
                    ->sortable(),

                Tables\Columns\TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'active' => 'success',
                        'suspended' => 'danger',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'active' => 'Activo',
                        'suspended' => 'Suspendido',
                    })
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('role')
                    ->relationship('role', 'display_name')
                    ->label('Filtrar por Rol'),
                Tables\Filters\SelectFilter::make('status')
                    ->label('Filtrar por Estado')
                    ->options([
                        'active' => 'Activos',
                        'suspended' => 'Suspendidos',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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