<?php

namespace App\Filament\Resources\Users;

use App\Filament\Resources\Users\Pages\CreateUser;
use App\Filament\Resources\Users\Pages\EditUser;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Models\TravelAgent;
use App\Models\User;
use BackedEnum;
use Filament\Actions;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

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

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-user-group';

    protected static ?string $navigationLabel = 'Users';

    protected static ?string $modelLabel = 'User';

    protected static ?string $pluralModelLabel = 'Users';

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                // Company Selection
                \Filament\Forms\Components\Select::make('travel_agent_id')
                    ->label('Company')
                    ->relationship('travelAgent', 'name')
                    ->required()
                    ->searchable()
                    ->preload()
                    ->options(TravelAgent::where('is_active', true)->pluck('name', 'id')),
                
                // User Information
                \Filament\Forms\Components\TextInput::make('name')
                    ->required()
                    ->maxLength(255),
                
                \Filament\Forms\Components\TextInput::make('email')
                    ->email()
                    ->required()
                    ->maxLength(255)
                    ->unique(ignorable: fn ($record) => $record),
                
                \Filament\Forms\Components\TextInput::make('mobile')
                    ->tel()
                    ->maxLength(255),
                
                \Filament\Forms\Components\TextInput::make('password')
                    ->password()
                    ->required()
                    ->maxLength(255)
                    ->dehydrated(fn ($state) => filled($state))
                    ->visible(fn (string $operation): bool => $operation === 'create'),
                
                \Filament\Forms\Components\TextInput::make('pin_code')
                    ->label('PIN Code')
                    ->maxLength(255),
                
                // Firebase and OTP
                \Filament\Forms\Components\TextInput::make('firebase_uid')
                    ->label('Firebase UID')
                    ->maxLength(255),
                
                \Filament\Forms\Components\TextInput::make('otp')
                    ->label('OTP')
                    ->maxLength(255),
                
                \Filament\Forms\Components\DateTimePicker::make('otp_expires_at')
                    ->label('OTP Expires At'),
                
                // Access Control
                \Filament\Forms\Components\DateTimePicker::make('access_expires_at')
                    ->label('Access Expires At'),
                
                \Filament\Forms\Components\DateTimePicker::make('last_login_at')
                    ->label('Last Login At'),
                
                \Filament\Forms\Components\TextInput::make('last_login_method')
                    ->label('Last Login Method')
                    ->maxLength(255),
                
                // Status and Permissions
                \Filament\Forms\Components\Toggle::make('is_admin')
                    ->label('Is Admin')
                    ->default(false),
                
                \Filament\Forms\Components\Toggle::make('is_active')
                    ->label('Active')
                    ->default(true)
                    ->helperText('Whether this user is active'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('travelAgent.name')
                    ->label('Company')
                    ->searchable()
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('email')
                    ->searchable(),
                
                Tables\Columns\TextColumn::make('mobile')
                    ->searchable(),
                
                Tables\Columns\IconColumn::make('is_admin')
                    ->label('Admin')
                    ->boolean()
                    ->sortable(),
                
                Tables\Columns\IconColumn::make('is_active')
                    ->label('Active')
                    ->boolean()
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('last_login_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('last_login_method')
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('access_expires_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('travel_agent_id')
                    ->label('Company')
                    ->relationship('travelAgent', 'name')
                    ->searchable()
                    ->preload(),
                
                Tables\Filters\TernaryFilter::make('is_admin')
                    ->label('Admin Users')
                    ->trueLabel('Admins Only')
                    ->falseLabel('Non-Admins Only'),
                
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status')
                    ->trueLabel('Active Only')
                    ->falseLabel('Inactive Only'),
            ])
            ->actions([
                Actions\EditAction::make(),
                Actions\Action::make('toggleStatus')
                    ->label(fn (User $record) => $record->is_active ? 'Deactivate' : 'Activate')
                    ->color(fn (User $record) => $record->is_active ? 'danger' : 'success')
                    ->action(function (User $record) {
                        $record->update(['is_active' => !$record->is_active]);
                    })
                    ->requiresConfirmation(),
                Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\DeleteBulkAction::make(),
                    Actions\BulkAction::make('activate')
                        ->action(fn ($records) => $records->each->update(['is_active' => true]))
                        ->requiresConfirmation(),
                    Actions\BulkAction::make('deactivate')
                        ->action(fn ($records) => $records->each->update(['is_active' => false]))
                        ->requiresConfirmation(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

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