<?php

namespace App\Filament\Resources\Users;

use App\Filament\Resources\Users\Pages\EditUser;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\Pages\ViewUser;
use App\Models\User;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use SensitiveParameter;

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

    protected static string|BackedEnum|null $navigationIcon = Heroicon::Users;

    protected static ?string $navigationLabel = 'Users';

    protected static string|\UnitEnum|null $navigationGroup = 'Platform';

    protected static ?int $navigationSort = 10;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->required()
                    ->maxLength(255),

                TextInput::make('email')
                    ->email()
                    ->required()
                    ->unique(ignoreRecord: true)
                    ->maxLength(255),

                TextInput::make('username')
                    ->unique(ignoreRecord: true)
                    ->rules(['nullable', 'alpha_dash:ascii'])
                    ->maxLength(80)
                    ->helperText('Optional frontend login username. Users can also set this from their profile.'),

                TextInput::make('password')
                    ->label('New password')
                    ->password()
                    ->revealable()
                    ->autocomplete('new-password')
                    ->formatStateUsing(fn (): ?string => null)
                    ->rule(Password::default())
                    ->dehydrated(fn (#[SensitiveParameter] $state): bool => filled($state))
                    ->dehydrateStateUsing(fn (#[SensitiveParameter] string $state): string => Hash::make($state))
                    ->helperText('Leave blank to keep the current password.'),

                TextInput::make('google_id')
                    ->label('Google ID')
                    ->maxLength(255),

                TextInput::make('avatar_url')
                    ->label('Avatar URL')
                    ->url()
                    ->maxLength(2048),

                Select::make('role')
                    ->required()
                    ->options([
                        'user' => 'User',
                        'admin' => 'Admin',
                    ]),

                DateTimePicker::make('email_verified_at')
                    ->label('Email verified at'),

                DateTimePicker::make('password_set_at')
                    ->label('Password set at'),

                DateTimePicker::make('questionnaire_completed_at')
                    ->label('Questionnaire completed at'),

                DateTimePicker::make('access_unlocked_at')
                    ->label('Access unlocked at'),

                DateTimePicker::make('resume_uploaded_at')
                    ->label('Resume uploaded at'),

                DateTimePicker::make('resume_analyzed_at')
                    ->label('Resume analyzed at'),

                DateTimePicker::make('profile_completed_at')
                    ->label('Profile completed at'),

                DateTimePicker::make('last_login_at')
                    ->label('Last login at'),
            ])
            ->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('email')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('username')
                    ->searchable()
                    ->toggleable(),

                TextColumn::make('role')
                    ->badge()
                    ->sortable(),

                IconColumn::make('questionnaire_completed_at')
                    ->label('Questionnaire')
                    ->state(fn (User $record): bool => $record->hasCompletedQuestionnaire())
                    ->boolean(),

                IconColumn::make('access_unlocked_at')
                    ->label('Paid')
                    ->state(fn (User $record): bool => $record->hasUnlockedAccess())
                    ->boolean(),

                IconColumn::make('resume_analyzed_at')
                    ->label('Resume')
                    ->state(fn (User $record): bool => $record->hasAnalyzedResume())
                    ->boolean(),

                IconColumn::make('profile_completed_at')
                    ->label('Profile')
                    ->state(fn (User $record): bool => $record->hasCompletedProfile())
                    ->boolean(),

                TextColumn::make('last_login_at')
                    ->dateTime()
                    ->sortable(),

                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('role')
                    ->options([
                        'user' => 'User',
                        'admin' => 'Admin',
                    ]),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->recordUrl(fn (User $record): string => static::getUrl('view', ['record' => $record]))
            ->defaultSort('created_at', 'desc');
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Applicant overview')
                    ->schema([
                        TextEntry::make('name')
                            ->label('Name'),

                        TextEntry::make('email')
                            ->label('Email')
                            ->copyable(),

                        TextEntry::make('username')
                            ->placeholder('Not set'),

                        TextEntry::make('role')
                            ->badge(),

                        TextEntry::make('applicant_status')
                            ->label('Applicant status')
                            ->state(fn (User $record): string => match (true) {
                                $record->canViewMatchedJobs() => 'Ready for matched jobs',
                                $record->hasAnalyzedResume() => 'Resume analyzed',
                                $record->hasUnlockedAccess() => 'Paid, resume pending',
                                $record->hasCompletedQuestionnaire() => 'Questionnaire completed',
                                default => 'Onboarding not started',
                            })
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'Ready for matched jobs' => 'success',
                                'Resume analyzed' => 'info',
                                'Paid, resume pending' => 'warning',
                                'Questionnaire completed' => 'gray',
                                default => 'danger',
                            }),

                        TextEntry::make('last_login_at')
                            ->dateTime()
                            ->placeholder('Never'),
                    ])
                    ->columns(3),

                Section::make('Onboarding checkpoints')
                    ->schema([
                        TextEntry::make('questionnaire_completed_at')
                            ->label('Questionnaire completed')
                            ->dateTime()
                            ->placeholder('Not completed'),

                        TextEntry::make('access_unlocked_at')
                            ->label('Access unlocked')
                            ->dateTime()
                            ->placeholder('Not unlocked'),

                        TextEntry::make('resume_uploaded_at')
                            ->label('Resume uploaded')
                            ->dateTime()
                            ->placeholder('Not uploaded'),

                        TextEntry::make('resume_analyzed_at')
                            ->label('Resume analyzed')
                            ->dateTime()
                            ->placeholder('Not analyzed'),

                        TextEntry::make('profile_completed_at')
                            ->label('Profile completed')
                            ->dateTime()
                            ->placeholder('Not completed'),

                        TextEntry::make('created_at')
                            ->label('Joined')
                            ->dateTime(),
                    ])
                    ->columns(3),

                Section::make('Job engagement database')
                    ->schema([
                        TextEntry::make('saved_jobs_count')
                            ->label('Saved jobs')
                            ->state(fn (User $record): int => $record->savedJobs()->count())
                            ->badge(),

                        TextEntry::make('applications_count')
                            ->label('Applied jobs')
                            ->state(fn (User $record): int => $record->applications()->count())
                            ->badge(),

                        TextEntry::make('job_interests_count')
                            ->label('Interested jobs')
                            ->state(fn (User $record): int => $record->jobInterests()->count())
                            ->badge(),

                        TextEntry::make('job_alert_status')
                            ->label('Job alerts')
                            ->state(fn (User $record): string => match (true) {
                                ! $record->jobAlertPreference => 'No preference yet',
                                ! $record->jobAlertPreference->isSubscribed() => 'Unsubscribed',
                                default => 'Subscribed',
                            })
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'Subscribed' => 'success',
                                'Unsubscribed' => 'danger',
                                default => 'gray',
                            }),

                        TextEntry::make('last_job_alert_sent_at')
                            ->label('Last alert sent')
                            ->state(fn (User $record): mixed => $record->jobAlertPreference?->last_sent_at)
                            ->dateTime()
                            ->placeholder('Never'),
                    ])
                    ->columns(5),

                Section::make('Profile summary')
                    ->schema([
                        TextEntry::make('profile.headline')
                            ->label('Headline')
                            ->placeholder('No profile headline'),

                        TextEntry::make('profile.current_role')
                            ->label('Current role')
                            ->placeholder('Not set'),

                        TextEntry::make('profile.experience_level')
                            ->label('Experience')
                            ->badge()
                            ->placeholder('Not set'),

                        TextEntry::make('profile.country_code')
                            ->label('Country')
                            ->placeholder('Not set'),

                        TextEntry::make('profile.skills')
                            ->label('Skills')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No skills saved')
                            ->columnSpanFull(),

                        TextEntry::make('profile.summary')
                            ->label('Summary')
                            ->placeholder('No profile summary')
                            ->columnSpanFull(),
                    ])
                    ->columns(3),

                Section::make('Questionnaire snapshot')
                    ->schema([
                        TextEntry::make('questionnaireResponse.preferred_categories')
                            ->label('Preferred categories')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No categories'),

                        TextEntry::make('questionnaireResponse.preferred_roles')
                            ->label('Preferred roles')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No roles'),

                        TextEntry::make('questionnaireResponse.salary_min')
                            ->label('Minimum salary')
                            ->money(fn (User $record): string => $record->questionnaireResponse?->salary_currency ?: 'USD')
                            ->placeholder('Not set'),

                        TextEntry::make('questionnaireResponse.preferred_timezone')
                            ->label('Preferred timezone')
                            ->placeholder('Not set'),
                    ])
                    ->columns(2),

                Section::make('Resume report')
                    ->schema([
                        TextEntry::make('resumeReport.original_filename')
                            ->label('Filename')
                            ->placeholder('No resume uploaded'),

                        TextEntry::make('resumeReport.status')
                            ->label('Analysis status')
                            ->badge()
                            ->placeholder('No report'),

                        TextEntry::make('resumeReport.ats_score')
                            ->label('ATS score')
                            ->placeholder('Not analyzed'),

                        TextEntry::make('resumeReport.remote_readiness_score')
                            ->label('Remote readiness')
                            ->placeholder('Not analyzed'),

                        TextEntry::make('resumeReport.extracted_skills')
                            ->label('Extracted skills')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No extracted skills')
                            ->columnSpanFull(),

                        TextEntry::make('resumeReport.analysis')
                            ->label('Structured analysis')
                            ->formatStateUsing(fn (mixed $state): ?string => is_array($state)
                                ? json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
                                : $state)
                            ->placeholder('No structured analysis')
                            ->copyable()
                            ->columnSpanFull(),
                    ])
                    ->columns(4),
            ]);
    }

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