<?php

namespace App\Filament\Resources;

use App\Filament\Resources\AnalyticsEventResource\Pages;
use App\Models\AnalyticsEvent;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Filters\SelectFilter;
use Illuminate\Database\Eloquent\Builder;

class AnalyticsEventResource extends Resource
{
    protected static ?string $model = AnalyticsEvent::class;

    protected static ?string $navigationIcon = 'heroicon-o-chart-bar';

    protected static ?string $navigationGroup = 'Analytics';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationLabel = 'Events';

    protected static ?string $pluralLabel = 'Analytics Events';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Event Details')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->relationship('user', 'tg_id')
                            ->searchable()
                            ->preload(),

                        Forms\Components\Select::make('event_type')
                            ->options([
                                AnalyticsEvent::TYPE_MESSAGE => 'Message',
                                AnalyticsEvent::TYPE_CALLBACK => 'Callback',
                                AnalyticsEvent::TYPE_SESSION_START => 'Session Start',
                                AnalyticsEvent::TYPE_SESSION_END => 'Session End',
                                AnalyticsEvent::TYPE_ERROR => 'Error',
                                AnalyticsEvent::TYPE_PAYMENT => 'Payment',
                                AnalyticsEvent::TYPE_MENU_VIEW => 'Menu View',
                                AnalyticsEvent::TYPE_CONTENT_VIEW => 'Content View',
                            ])
                            ->required(),

                        Forms\Components\DateTimePicker::make('created_at')
                            ->default(now())
                            ->required(),
                    ]),

                Forms\Components\Section::make('Event Data')
                    ->schema([
                        Forms\Components\Textarea::make('event_data')
                            ->label('Event Data (JSON)')
                            ->rows(5)
                            ->formatStateUsing(fn ($state) => json_encode($state, JSON_PRETTY_PRINT))
                            ->dehydrateStateUsing(fn ($state) => json_decode($state, true)),
                    ]),

                Forms\Components\Section::make('Technical Details')
                    ->schema([
                        Forms\Components\TextInput::make('ip_address')
                            ->maxLength(45),

                        Forms\Components\Textarea::make('user_agent')
                            ->rows(2),
                    ])
                    ->collapsible()
                    ->collapsed(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->sortable(),

                Tables\Columns\TextColumn::make('user.tg_id')
                    ->label('User')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('event_type')
                    ->label('Type')
                    ->color(fn (string $state): string => match ($state) {
                        AnalyticsEvent::TYPE_MESSAGE => 'info',
                        AnalyticsEvent::TYPE_CALLBACK => 'success',
                        AnalyticsEvent::TYPE_SESSION_START => 'success',
                        AnalyticsEvent::TYPE_SESSION_END => 'gray',
                        AnalyticsEvent::TYPE_ERROR => 'danger',
                        AnalyticsEvent::TYPE_PAYMENT => 'warning',
                        AnalyticsEvent::TYPE_MENU_VIEW => 'info',
                        AnalyticsEvent::TYPE_CONTENT_VIEW => 'primary',
                        default => 'secondary',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        AnalyticsEvent::TYPE_MESSAGE => 'Message',
                        AnalyticsEvent::TYPE_CALLBACK => 'Callback',
                        AnalyticsEvent::TYPE_SESSION_START => 'Session Start',
                        AnalyticsEvent::TYPE_SESSION_END => 'Session End',
                        AnalyticsEvent::TYPE_ERROR => 'Error',
                        AnalyticsEvent::TYPE_PAYMENT => 'Payment',
                        AnalyticsEvent::TYPE_MENU_VIEW => 'Menu View',
                        AnalyticsEvent::TYPE_CONTENT_VIEW => 'Content View',
                        default => ucfirst($state),
                    }),

                Tables\Columns\TextColumn::make('description')
                    ->label('Description')
                    ->limit(50)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        return $column->getRecord()->description;
                    }),

                Tables\Columns\TextColumn::make('command')
                    ->label('Command')
                    ->placeholder('—')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('callback_data')
                    ->label('Callback Data')
                    ->limit(30)
                    ->placeholder('—')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('ip_address')
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('event_type')
                    ->label('Event Type')
                    ->options([
                        AnalyticsEvent::TYPE_MESSAGE => 'Message',
                        AnalyticsEvent::TYPE_CALLBACK => 'Callback',
                        AnalyticsEvent::TYPE_SESSION_START => 'Session Start',
                        AnalyticsEvent::TYPE_SESSION_END => 'Session End',
                        AnalyticsEvent::TYPE_ERROR => 'Error',
                        AnalyticsEvent::TYPE_PAYMENT => 'Payment',
                        AnalyticsEvent::TYPE_MENU_VIEW => 'Menu View',
                        AnalyticsEvent::TYPE_CONTENT_VIEW => 'Content View',
                    ]),

                SelectFilter::make('user_id')
                    ->label('User')
                    ->relationship('user', 'tg_id')
                    ->searchable()
                    ->preload(),

                Tables\Filters\Filter::make('created_at')
                    ->form([
                        Forms\Components\DatePicker::make('created_from'),
                        Forms\Components\DatePicker::make('created_until'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
                            )
                            ->when(
                                $data['created_until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
                            );
                    }),

                Tables\Filters\Filter::make('commands_only')
                    ->label('Commands Only')
                    ->query(fn (Builder $query): Builder => $query->commands()),

                Tables\Filters\Filter::make('callbacks_only')
                    ->label('Callbacks Only')
                    ->query(fn (Builder $query): Builder => $query->callbacks()),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAnalyticsEvents::route('/'),
            'view' => Pages\ViewAnalyticsEvent::route('/{record}'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::whereDate('created_at', today())->count();
    }

    public static function canCreate(): bool
    {
        return false; // Analytics events are created automatically
    }

    public static function canEdit($record): bool
    {
        return false; // Analytics events should not be edited
    }
}