<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Actions;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

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

    public static function getNavigationIcon(): string { return 'heroicon-o-users'; }
    public static function getNavigationGroup(): string { return 'Users'; }
    public static function getNavigationSort(): int { return 1; }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Account Info')->schema([
                TextInput::make('name')->required()->maxLength(255),
                TextInput::make('username')->unique(ignoreRecord: true)->minLength(3)->maxLength(30),
                TextInput::make('email')->email()->required()->unique(ignoreRecord: true),
                TextInput::make('password')
                    ->password()
                    ->revealable()
                    ->dehydrateStateUsing(fn($state) => Hash::make($state))
                    ->dehydrated(fn($state) => filled($state))
                    ->required(fn(string $context) => $context === 'create'),
                Select::make('roles')
                    ->label('Role')
                    ->options(Role::all()->pluck('name', 'name'))
                    ->multiple()
                    ->preload(),
            ])->columns(2),

            Section::make('Wallet & Status')->schema([
                TextInput::make('balance')->numeric()->prefix('$')->default(500)->required(),
                Select::make('vip_tier')
                    ->options(['bronze' => 'Bronze', 'silver' => 'Silver', 'gold' => 'Gold', 'platinum' => 'Platinum', 'diamond' => 'Diamond'])
                    ->default('bronze'),
                TextInput::make('vip_points')->numeric()->default(0),
                Toggle::make('is_active')->default(true)->label('Account Active'),
                DateTimePicker::make('email_verified_at')->label('Email Verified'),
            ])->columns(3),

            Section::make('Preferences')->schema([
                Toggle::make('email_notifications')->default(true),
                Toggle::make('promotional_offers')->default(false),
                Toggle::make('security_alerts')->default(true),
            ])->columns(3),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')->sortable()->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('username')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('email')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('balance')->money('USD')->sortable(),
                Tables\Columns\TextColumn::make('roles.name')->badge()->label('Roles'),
                Tables\Columns\TextColumn::make('vip_tier')->badge()
                    ->color(fn(string $state) => match($state) {
                        'bronze' => 'warning', 'silver' => 'gray', 'gold' => 'success',
                        'platinum' => 'info', 'diamond' => 'danger', default => 'gray',
                    }),
                Tables\Columns\IconColumn::make('is_active')->boolean()->label('Active'),
                Tables\Columns\IconColumn::make('email_verified_at')->boolean()->label('Verified')
                    ->state(fn($record) => !is_null($record->email_verified_at)),
                Tables\Columns\TextColumn::make('created_at')->dateTime()->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('vip_tier')
                    ->options(['bronze' => 'Bronze', 'silver' => 'Silver', 'gold' => 'Gold', 'platinum' => 'Platinum']),
                Tables\Filters\TernaryFilter::make('is_active')->label('Account Status'),
            ])
            ->recordActions([
                Actions\EditAction::make(),
                Actions\Action::make('toggle_active')
                    ->label(fn($record) => $record->is_active ? 'Suspend' : 'Activate')
                    ->icon(fn($record) => $record->is_active ? 'heroicon-o-no-symbol' : 'heroicon-o-check-circle')
                    ->color(fn($record) => $record->is_active ? 'danger' : 'success')
                    ->requiresConfirmation()
                    ->action(fn($record) => $record->update(['is_active' => !$record->is_active])),
            ])
            ->toolbarActions([
                Actions\BulkActionGroup::make([
                    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'),
        ];
    }
}
