<?php

namespace App\Filament\Resources\Trainings;

use App\Filament\Resources\Trainings\Pages\CreateTraining;
use App\Filament\Resources\Trainings\Pages\EditTraining;
use App\Filament\Resources\Trainings\Pages\ListTrainings;
use App\Filament\Resources\Trainings\RelationManagers\FeedbackSubmissionsRelationManager;
use App\Models\Training;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class TrainingResource extends Resource
{
    protected static ?string $model = Training::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-presentation-chart-bar';

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

    protected static ?string $navigationLabel = 'Trainings';

    protected static ?int $navigationSort = 5;

    protected static ?string $recordTitleAttribute = 'title';

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Training & feedback form')
                ->description('Create the training first, then share its unique link. Every response from that link is filed under this training automatically.')
                ->columns(2)
                ->schema([
                    TextInput::make('title')
                        ->label('Training / session name')
                        ->required()
                        ->maxLength(255)
                        ->live(onBlur: true)
                        ->afterStateUpdated(fn ($state, callable $set, Get $get) => filled($get('slug')) ? null : $set('slug', Str::slug($state ?? ''))),
                    TextInput::make('slug')
                        ->label('Feedback link name')
                        ->required()
                        ->maxLength(255)
                        ->unique(ignoreRecord: true)
                        ->helperText('Lowercase words separated by hyphens. This becomes part of the public feedback URL.'),
                    TextInput::make('organization')
                        ->label('Client / organization')
                        ->maxLength(255),
                    DatePicker::make('training_date')
                        ->label('Training date'),
                    TextInput::make('facilitator')
                        ->label('Facilitator / trainer')
                        ->maxLength(255),
                    TextInput::make('audience_segment')
                        ->label('Audience profile')
                        ->maxLength(255),
                    TextInput::make('expected_attendees')
                        ->label('Expected attendees')
                        ->numeric()
                        ->minValue(1),
                    Textarea::make('intro')
                        ->label('Message shown on the feedback form')
                        ->rows(3)
                        ->placeholder('Thank attendees or add a short instruction for this session.')
                        ->columnSpanFull(),
                    Repeater::make('resources')
                        ->label('Resources shared with attendees')
                        ->schema([
                            TextInput::make('label')->required(),
                            TextInput::make('url')->url()->required(),
                        ])
                        ->columns(2)
                        ->addActionLabel('Add resource')
                        ->columnSpanFull(),
                    DateTimePicker::make('feedback_closes_at')
                        ->label('Stop accepting feedback at')
                        ->helperText('Optional. Leave empty to keep accepting responses.'),
                    Toggle::make('is_active')
                        ->label('Feedback link active')
                        ->default(true)
                        ->inline(false),
                    Placeholder::make('share_link')
                        ->label('Unique feedback link')
                        ->visible(fn (Get $get) => filled($get('slug')))
                        ->content(fn (Get $get) => url('/feedback/'.$get('slug')))
                        ->columnSpanFull(),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('training_date', 'desc')
            ->columns([
                TextColumn::make('title')->searchable()->weight('bold')->wrap(),
                TextColumn::make('organization')->searchable()->placeholder('Not specified')->toggleable(),
                TextColumn::make('training_date')->date('j M Y')->sortable()->placeholder('Not set'),
                TextColumn::make('facilitator')->searchable()->placeholder('Not set')->toggleable(),
                TextColumn::make('feedbacks_count')->label('Submissions')->badge()->sortable(),
                TextColumn::make('participation')
                    ->label('Participation')
                    ->getStateUsing(fn (Training $record) => $record->expected_attendees
                        ? $record->feedbacks_count.' / '.$record->expected_attendees
                        : (string) $record->feedbacks_count)
                    ->description('feedback / expected'),
                TextColumn::make('feedbacks_avg_overall_experience')
                    ->label('Avg. rating')
                    ->formatStateUsing(fn ($state) => filled($state) ? number_format((float) $state, 1).' / 5' : '—')
                    ->sortable(),
                TextColumn::make('feedbackUrl')
                    ->label('Feedback link')
                    ->getStateUsing(fn (Training $record) => $record->feedbackUrl())
                    ->copyable()
                    ->copyMessage('Feedback link copied')
                    ->limit(42)
                    ->color('primary'),
                IconColumn::make('is_active')->boolean()->label('Active'),
            ])
            ->recordActions([
                EditAction::make(),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withCount('feedbacks')
            ->withAvg('feedbacks', 'overall_experience');
    }

    public static function getRelations(): array
    {
        return [
            FeedbackSubmissionsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListTrainings::route('/'),
            'create' => CreateTraining::route('/create'),
            'edit' => EditTraining::route('/{record}/edit'),
        ];
    }
}
