<?php

namespace App\Filament\Resources\QuestionnaireResponses;

use App\Filament\Resources\QuestionnaireResponses\Pages\EditQuestionnaireResponse;
use App\Filament\Resources\QuestionnaireResponses\Pages\ListQuestionnaireResponses;
use App\Filament\Resources\QuestionnaireResponses\Pages\ViewQuestionnaireResponse;
use App\Models\QuestionnaireResponse;
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\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
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;

class QuestionnaireResponseResource extends Resource
{
    protected static ?string $model = QuestionnaireResponse::class;

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

    protected static ?string $navigationLabel = 'Questionnaire';

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

    protected static ?int $navigationSort = 25;

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Select::make('user_id')
                    ->relationship('user', 'email')
                    ->searchable()
                    ->preload()
                    ->required()
                    ->unique(ignoreRecord: true),

                TagsInput::make('preferred_categories')
                    ->label('Preferred categories')
                    ->placeholder('Add a category'),

                TagsInput::make('preferred_roles')
                    ->label('Preferred roles')
                    ->placeholder('Add a role'),

                TagsInput::make('skills')
                    ->placeholder('Add a skill'),

                Select::make('experience_level')
                    ->options([
                        'entry' => 'Entry',
                        'junior' => 'Junior',
                        'mid' => 'Mid',
                        'senior' => 'Senior',
                        'lead' => 'Lead',
                    ]),

                Select::make('availability')
                    ->options([
                        'immediate' => 'Immediate',
                        'two_weeks' => 'Two weeks',
                        'one_month' => 'One month',
                        'flexible' => 'Flexible',
                    ]),

                TextInput::make('preferred_timezone')
                    ->maxLength(80),

                TextInput::make('country_code')
                    ->maxLength(2),

                TextInput::make('salary_currency')
                    ->required()
                    ->maxLength(3),

                TextInput::make('salary_min')
                    ->numeric()
                    ->minValue(0),

                Toggle::make('open_to_contract'),

                Toggle::make('open_to_full_time'),

                DateTimePicker::make('completed_at'),
            ])
            ->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('user.email')
                    ->label('User')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('preferred_categories')
                    ->label('Categories')
                    ->formatStateUsing(fn (mixed $state): string => collect($state)->take(3)->implode(', '))
                    ->limit(45),

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

                TextColumn::make('country_code')
                    ->label('Country')
                    ->sortable(),

                TextColumn::make('salary_min')
                    ->label('Min salary')
                    ->money(fn (QuestionnaireResponse $record): string => $record->salary_currency)
                    ->sortable(),

                IconColumn::make('open_to_contract')
                    ->boolean()
                    ->sortable(),

                IconColumn::make('open_to_full_time')
                    ->boolean()
                    ->sortable(),

                TextColumn::make('completed_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('experience_level')
                    ->options([
                        'entry' => 'Entry',
                        'junior' => 'Junior',
                        'mid' => 'Mid',
                        'senior' => 'Senior',
                        'lead' => 'Lead',
                    ]),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->recordUrl(fn (QuestionnaireResponse $record): string => static::getUrl('view', ['record' => $record]))
            ->defaultSort('completed_at', 'desc');
    }

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

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

                        TextEntry::make('completed_at')
                            ->label('Completed at')
                            ->dateTime()
                            ->placeholder('Not completed'),
                    ])
                    ->columns(3),

                Section::make('Preferences')
                    ->schema([
                        TextEntry::make('preferred_categories')
                            ->label('Categories')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No categories'),

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

                        TextEntry::make('skills')
                            ->label('Skills')
                            ->listWithLineBreaks()
                            ->badge()
                            ->placeholder('No skills'),
                    ])
                    ->columns(3),

                Section::make('Work requirements')
                    ->schema([
                        TextEntry::make('experience_level')
                            ->label('Experience')
                            ->badge()
                            ->placeholder('Not set'),

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

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

                        TextEntry::make('preferred_timezone')
                            ->label('Timezone')
                            ->placeholder('Not set'),

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

                        TextEntry::make('work_format')
                            ->label('Work format')
                            ->state(fn (QuestionnaireResponse $record): string => collect([
                                $record->open_to_full_time ? 'Full-time' : null,
                                $record->open_to_contract ? 'Contract' : null,
                            ])->filter()->implode(', ') ?: 'Not set')
                            ->badge(),
                    ])
                    ->columns(3),

                Section::make('Structured answers')
                    ->schema([
                        TextEntry::make('answers')
                            ->formatStateUsing(fn (mixed $state): ?string => is_array($state)
                                ? json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
                                : $state)
                            ->copyable()
                            ->placeholder('No answer payload stored')
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),
            ]);
    }
}
