<?php

namespace App\Livewire\Clients;

use App\Models\{User};

use Illuminate\Http\Request;

use Illuminate\Support\{Str,Carbon};
use Illuminate\Support\HtmlString;
use Illuminate\Support\Facades\{Auth,DB};
use Illuminate\Database\Eloquent\Builder;

use Livewire\Component;
use Filament\Notifications\Notification;

use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\ViewColumn;
use Filament\Actions\{Action, BulkAction, CreateAction};
use Filament\Forms\Components\{TextInput, Select};
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;

class Overview extends Component implements HasTable, HasSchemas, HasActions
{
    use InteractsWithActions;
    use InteractsWithSchemas;
    use InteractsWithTable;

    public function makeFilamentTranslatableContentDriver(): ?\Filament\Support\Contracts\TranslatableContentDriver
    {
        return null;
    }

    public function table(Table $table): Table
    {
        $isAdmin = auth()->user()->hasanyrole('superadmin','admin');

        $query = User::query()
            ->select('users.*')
            ->selectRaw('(SELECT COUNT(*) FROM sessions WHERE sessions.user_id = users.id AND sessions.user_id IS NOT NULL) as is_online');

        $headerActions = [];

        if ($isAdmin) {
            $headerActions[] = Action::make('create_customer')
                ->label('Create Customer')
                ->color('primary')
                ->button()
                ->extraAttributes(['class' => '!bg-indigo-700 hover:!bg-indigo-500 !text-white'])
                ->form([
                    TextInput::make('name')
                        ->label('Full Name')
                        ->required()
                        ->markAsRequired(false)
                        ->maxLength(255)
                        ->placeholder('e.g., John Doe')
                        ->extraAttributes(['style' => 'margin-bottom: 1.25rem; margin-top: 0.5rem;']),

                    TextInput::make('email')
                        ->label('Email Address')
                        ->email()
                        ->required()
                        ->markAsRequired(false)
                        ->unique(User::class, 'email')
                        ->maxLength(255)
                        ->placeholder('e.g., john@example.com')
                        ->extraAttributes(['style' => 'margin-bottom: 1.25rem; margin-top: 0.5rem;']),

                    TextInput::make('company')
                        ->label(fn () => new HtmlString('Company Name <span style="background-color: rgb(229, 231, 235); color: rgb(75, 85, 99); padding: 2px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 500; margin-left: 8px;">Optional</span>'))
                        ->maxLength(255)
                        ->placeholder('e.g., Acme Corporation')
                        ->prefixIcon('heroicon-o-building-office-2')
                        ->extraAttributes(['style' => 'margin-bottom: 1.25rem; margin-top: 0.5rem;']),

                    Select::make('account_manager')
                        ->label(fn () => new HtmlString('Account Manager <span style="background-color: rgb(229, 231, 235); color: rgb(75, 85, 99); padding: 2px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 500; margin-left: 8px;">Optional</span>'))
                        ->options(function () {
                            return User::whereHas('roles', function ($query) {
                                $query->whereIn('name', ['superadmin', 'admin', 'employee']);
                            })->pluck('name', 'id');
                        })
                        ->searchable()
                        ->placeholder('Select an account manager')
                        ->prefixIcon('heroicon-o-user-circle')
                        ->extraAttributes(['style' => 'margin-bottom: 1.25rem; margin-top: 0.5rem;']),

                    Select::make('role')
                        ->label('Role')
                        ->options(function () {
                            $options = [
                                'customer' => 'Customer',
                                'employee' => 'Employee',
                                'admin' => 'Admin',
                            ];

                            // Only show superadmin option to superadmins
                            if (auth()->user()->hasRole('superadmin')) {
                                $options['superadmin'] = 'Super Admin';
                            }

                            return $options;
                        })
                        ->default('customer')
                        ->required()
                        ->prefixIcon('heroicon-o-shield-check')
                        ->visible(fn () => auth()->user()->hasRole(['superadmin', 'admin']))
                        ->extraAttributes(['style' => 'margin-bottom: 1.25rem; margin-top: 0.5rem;']),

                    TextInput::make('custom_password')
                        ->label(fn () => new HtmlString('Password <span style="background-color: rgb(229, 231, 235); color: rgb(75, 85, 99); padding: 2px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 500; margin-left: 8px;">Optional</span>'))
                        ->password()
                        ->revealable()
                        ->maxLength(255)
                        ->placeholder('Leave blank to auto-generate')
                        ->helperText('If left blank, a random password will be generated')
                        ->minLength(8)
                        ->extraAttributes(['style' => 'margin-top: 0.5rem;'])
                        ->suffixAction(
                            Action::make('generate')
                                ->icon('heroicon-o-sparkles')
                                ->action(function ($set) {
                                    // Generate a secure password with letters, numbers, and symbols
                                    $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                                    $lowercase = 'abcdefghijklmnopqrstuvwxyz';
                                    $numbers = '0123456789';
                                    $symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';

                                    $password = '';
                                    $password .= $uppercase[random_int(0, strlen($uppercase) - 1)];
                                    $password .= $lowercase[random_int(0, strlen($lowercase) - 1)];
                                    $password .= $numbers[random_int(0, strlen($numbers) - 1)];
                                    $password .= $symbols[random_int(0, strlen($symbols) - 1)];

                                    $allCharacters = $uppercase . $lowercase . $numbers . $symbols;
                                    for ($i = 0; $i < 12; $i++) {
                                        $password .= $allCharacters[random_int(0, strlen($allCharacters) - 1)];
                                    }

                                    $password = str_shuffle($password);
                                    $set('custom_password', $password);
                                })
                        ),
                ])
                ->action(function (array $data) {
                    // Use custom password if provided, otherwise generate a random one with symbols
                    if (!empty($data['custom_password'])) {
                        $password = $data['custom_password'];
                    } else {
                        $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        $lowercase = 'abcdefghijklmnopqrstuvwxyz';
                        $numbers = '0123456789';
                        $symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';

                        $password = '';
                        $password .= $uppercase[random_int(0, strlen($uppercase) - 1)];
                        $password .= $lowercase[random_int(0, strlen($lowercase) - 1)];
                        $password .= $numbers[random_int(0, strlen($numbers) - 1)];
                        $password .= $symbols[random_int(0, strlen($symbols) - 1)];

                        $allCharacters = $uppercase . $lowercase . $numbers . $symbols;
                        for ($i = 0; $i < 12; $i++) {
                            $password .= $allCharacters[random_int(0, strlen($allCharacters) - 1)];
                        }

                        $password = str_shuffle($password);
                    }

                    $user = User::create([
                        'name' => $data['name'],
                        'email' => $data['email'],
                        'company' => $data['company'] ?? null,
                        'password' => Hash::make($password),
                        'account_manager' => $data['account_manager'] ?? 0,
                        'biography' => '',
                        'force_password_reset' => true,
                    ]);

                    // Assign the selected role (defaults to 'customer' if not provided)
                    $user->assignRole($data['role'] ?? 'customer');

                    event(new Registered($user));

                    // TODO: Send email with temporary password to user
                    // For now, show the temp password in the notification (remove this in production)
                    $roleLabel = ucfirst($data['role'] ?? 'customer');
                    Notification::make()
                        ->title('User Created Successfully')
                        ->body("{$roleLabel} {$user->name} has been created. Temporary password: {$password} (Send this to the user securely)")
                        ->success()
                        ->duration(10000)
                        ->send();
                })
                ->modalHeading('Create New Customer')
                ->modalDescription('Create a new customer account. The customer will be required to change their password on first login.')
                ->modalSubmitActionLabel('Create Customer')
                ->modalWidth('xl');
        }

        return $table
            ->query($query)
            ->heading('Customers')
            ->columns([
                ViewColumn::make('avatar')
                    ->label('')
                    ->view('filament.tables.columns.user-avatar')
                    ->extraAttributes(['class' => 'w-24']),

                TextColumn::make('name')
                    ->label(strtoupper(__('Name')))
                    ->searchable()
                    ->sortable()
                    ->extraAttributes(['class' => 'font-medium']),

                TextColumn::make('company')
                    ->label(strtoupper(__('Company')))
                    ->searchable()
                    ->sortable()
                    ->placeholder('—'),

                TextColumn::make('email')
                    ->label(strtoupper(__('Email Address')))
                    ->searchable()
                    ->sortable()
                    ->copyable()
                    ->copyMessage('Email copied!')
                    ->icon('heroicon-o-envelope'),

                TextColumn::make('account_manager_name')
                    ->label(strtoupper(__('Account Manager')))
                    ->getStateUsing(function ($record) {
                        if ($record->account_manager) {
                            $manager = User::find($record->account_manager);
                            return $manager ? $manager->name : '—';
                        }
                        return '—';
                    })
                    ->placeholder('—'),
            ])
            ->defaultSort('id', 'desc')
            ->actions([
                Action::make('view')
                    ->label('View')
                    ->button()
                    ->size('sm')
                    ->color('primary')
                    ->url(fn (User $record): string =>
                        $record->id != Auth::user()->id
                            ? route('view_client', ['clientId' => $record->id])
                            : route('settings.profile')
                    )
                    ->extraAttributes(['class' => '!bg-indigo-700 hover:!bg-indigo-500 !text-white'])
            ])
            ->headerActions($headerActions)
            ->emptyStateHeading(__("Currently there aren't any customers."))
            ->emptyStateIcon('heroicon-o-users')
            ->poll('5s')
            ->striped()
            ->paginated([10, 25, 50, 100]);
    }

    public function render()
    {
        return view('livewire.clients.overview');
    }
}
