<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Models\Enum\BookingStatusEnum;
use App\Models\Enum\RoleEnum;
use App\Models\Role;
use App\Models\Side;
use App\Models\User;
use App\Models\UserSession;
use App\Models\UserType;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;

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

    protected static ?string $navigationGroup = "User Management";

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

    public static function canViewAny(): bool
    {
        return auth()->user()->role_id !== RoleEnum::ID[RoleEnum::SIDE_USER];
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label('Full Name')
                    ->required()
                    ->maxLength(255),

                Forms\Components\TextInput::make('identifier')
                    ->label('Identifier')
                    ->nullable(),

                Forms\Components\TextInput::make('email')
                    ->label('Email')
                    ->email()
                    ->required()
                    ->unique(User::class, 'email', fn($record) => $record),

                Forms\Components\TextInput::make('password')
                    ->label('Password')
                    ->password()
                    ->required(fn($context) => $context === 'create')
                    ->minLength(8)
                    ->dehydrateStateUsing(fn ($state) => bcrypt($state))
                    ->visible(fn($record) => !$record),

                Forms\Components\TextInput::make('pin')
                    ->label('Pin')
                    ->nullable(),

                Forms\Components\TextInput::make('sierra_record_number')
                    ->label('Sierra Record Number')
                    ->nullable(),

                Forms\Components\Select::make('sex')
                    ->label('Sex')
                    ->options([
                        'male' => 'Male',
                        'female' => 'Female',
                    ])
                    ->nullable(),

                Forms\Components\TextInput::make('sierra_type')
                    ->label('Sierra Type')
                    ->nullable(),

                Forms\Components\TextInput::make('record_number')
                    ->label('Record Number')
                    ->nullable(),

                Forms\Components\DatePicker::make('birth')
                    ->label('Birth Date')
                    ->nullable(),

                Forms\Components\TextInput::make('location')
                    ->label('Location')
                    ->nullable(),

                Forms\Components\TextInput::make('town')
                    ->label('Town')
                    ->nullable(),

                Forms\Components\TextInput::make('country_born')
                    ->label('Country Born')
                    ->nullable(),

                Forms\Components\Select::make('principal_library')
                    ->label('Principal Library')
                    ->searchable()
                    ->options(Side::all()->pluck('name', 'id'))
                    ->required(),

                Forms\Components\DateTimePicker::make('lock_date_until')
                    ->label('Lock Date Until')
                    ->nullable(),

                Forms\Components\TextInput::make('notice_number')
                    ->label('Notice Number')
                    ->nullable(),

                Forms\Components\TextInput::make('address')
                    ->label('Address')
                    ->nullable(),

                Forms\Components\Toggle::make('locked')
                    ->label('Locked')
                    ->nullable(),

                Forms\Components\Select::make('role_id')
                    ->label('Role')
                    ->searchable()
                    ->options(Role::all()->pluck('name', 'id'))
                    ->required(),

                Forms\Components\Select::make('user_type_id')
                    ->label('User Type')
                    ->searchable()
                    ->options(UserType::all()->pluck('name', 'id'))
                    ->required(),
            ]);
    }

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

                Tables\Columns\TextColumn::make("userType.name")
                    ->label('User Type')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('active_bookings_count')
                    ->label('Active Bookings')
                    ->getStateUsing(function ($record) {
                        return $record->bookings()
                            ->where("booking_status_id", BookingStatusEnum::ID[BookingStatusEnum::CONFIRMED])
                            ->count()
                        ;
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('userSessions')
                    ->label('Last Session')
                    ->getStateUsing(function ($record) {
                        $lastSession = $record->bookings()->latest()->first()?->userSession;

                        return $lastSession ? \Carbon\Carbon::parse($lastSession->start_time)->format('d/m/Y H:i') : 'No session';
                    })
                    ->badge(fn($state) => $state ? 'success' : 'danger'),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('name')
                    ->label('Full Name')
                    ->options(User::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select User Full Name'),

                Tables\Filters\SelectFilter::make('user_type_id')
                    ->label('User Type')
                    ->options(UserType::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select User Type'),

                Tables\Filters\SelectFilter::make('principal_library')
                    ->label('Principal Side (Library)')
                    ->options(Side::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Side (Library)'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),

                Tables\Actions\Action::make('go_to_bookings')
                    ->label('Go to Bookings')
                    ->icon('heroicon-o-calendar-date-range')
                    ->url(fn ($record) => "/admin/bookings?tableFilters[user_id][value]=". $record->id),

                Tables\Actions\Action::make('reset_password')
                    ->label('Reset Password')
                    ->icon('heroicon-o-key')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading('Reset User Password')
                    ->modalSubmitActionLabel('Reset Password')
                    ->form([
                        Forms\Components\TextInput::make('new_password')
                            ->label('New Password')
                            ->password()
                            ->required()
                            ->minLength(8)
                            ->same('confirm_password')->label('Confirm Password'),
                        Forms\Components\TextInput::make('confirm_password')
                            ->label('Confirm Password')
                            ->password()
                            ->required()
                            ->minLength(8),
                    ])
                    ->action(function ($record, array $data) {
                        $newPassword = $data['new_password'];
                        $confirmPassword = $data['confirm_password'];

                        if ($newPassword !== $confirmPassword) {
                            session()->flash('error', 'Passwords do not match.');
                            return;
                        }

                        $user = $record;

                        $user->update([
                            'password' => Hash::make($newPassword),
                        ]);

                        session()->flash('success', 'Password has been reset successfully.');
                    }),
            ])
            ->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'),
        ];
    }
}
