<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use STS\FilamentImpersonate\Tables\Actions\Impersonate;
use Ysfkaya\FilamentPhoneInput\Forms\PhoneInput;
use Ysfkaya\FilamentPhoneInput\PhoneInputNumberType;
use Ysfkaya\FilamentPhoneInput\Tables\PhoneColumn;

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

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

    protected static ?int $navigationSort = 7;

    public static function getNavigationLabel(): string
    {
        return __('common.users');
    }

    public static function getModelLabel(): string
    {
        return __('common.user');
    }

    public static function getPluralModelLabel(): string
    {
        return __('common.users');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.user_management');
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',

            'can_impersonate',
        ];
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label(__('common.name'))
                    ->required(),

                Forms\Components\TextInput::make('job_title')
                    ->label(__('common.job_title'))
                    ->maxLength(255),

                Forms\Components\TextInput::make('email')
                    ->label(__('common.email'))
                    ->email()
                    ->required()
                    ->unique(ignoreRecord: true),

                PhoneInput::make('phone_number')
                    ->label(__('common.phone_number'))
                    ->defaultCountry('SA')
                    ->onlyCountries(['sa'])
                    ->validateFor('SA')
                    ->displayNumberFormat(PhoneInputNumberType::NATIONAL)
                    ->inputNumberFormat(PhoneInputNumberType::E164)
                    ->separateDialCode(true)
                    ->disallowDropdown()
                    ->unique(ignoreRecord: true),

                Forms\Components\Select::make('roles')
                    ->label(__('common.roles'))
                    ->multiple()
                    ->relationship('roles', 'name')
                    ->preload()
                    ->options(Role::pluck('name', 'id')->toArray()),

                Forms\Components\Select::make('departments')
                    ->label(__('common.departments'))
                    ->multiple()
                    ->relationship('departments', 'name')
                    ->preload()
                    ->searchable(),

                // Hidden password fields - defaulting to TempPassword@123 since password login is not used
                Forms\Components\Hidden::make('password')
                    ->default('TempPassword@123')
                    ->dehydrateStateUsing(fn ($state) => Hash::make($state)),

                Forms\Components\Hidden::make('password_confirmation')
                    ->default('TempPassword@123'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('common.name'))
                    ->sortable()
                    ->searchable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->name)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('job_title')
                    ->label(__('common.job_title'))
                    ->sortable()
                    ->searchable()
                    ->placeholder('—')
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->job_title)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('email')
                    ->label(__('common.email'))
                    ->sortable()
                    ->searchable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->email)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('association.name')
                    ->label(__('common.association'))
                    ->sortable()
                    ->searchable()
                    ->placeholder(__('common.no_association'))
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->association?->name)
                    ->toggleable(),

                PhoneColumn::make('phone_number')
                    ->label(__('common.phone_number'))
                    ->displayFormat(PhoneInputNumberType::NATIONAL)
                    ->sortable()
                    ->searchable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('roles.name')
                    ->label(__('common.roles'))
                    ->badge()
                    ->separator(', ')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('common.created_at'))
                    ->date()
                    ->toggleable(isToggledHiddenByDefault: true),

            ])
            ->filters([
                Tables\Filters\SelectFilter::make('roles')
                    ->label(__('common.roles'))
                    ->relationship('roles', 'name')
                    ->multiple()
                    ->preload(),
            ])
            ->headerActions([
                Tables\Actions\ExportAction::make()
                    ->exporter(\App\Filament\Exports\UserExporter::class),
            ])
            ->actions([
                Impersonate::make()
                    ->redirectTo(function (User $user): string {
                        // if the user has an association, redirect to the association admin panel
                        if ($user->association) {
                            return '/association-admin';
                        }

                        return '/admin';
                    }),
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            UserResource\RelationManagers\DonorFinancialPortfoliosRelationManager::class,
        ];
    }

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