<?php

namespace App\Filament\Resources;

use App\Filament\Resources\EventResource\Pages;
use App\Models\Event;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class EventResource extends Resource
{
    protected static ?string $model = Event::class;
    protected static ?string $navigationIcon = 'heroicon-o-calendar';
    protected static ?string $navigationGroup = 'Public Engagement';
    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('Event Information')
                    ->columns(2)
                    ->schema([
                        TextInput::make('title')
                            ->required()
                            ->maxLength(255)
                            ->columnSpanFull(),

                        Textarea::make('description')
                            ->required()
                            ->rows(4)
                            ->columnSpanFull(),

                        Select::make('event_type')
                            ->options([
                                'public_hearing' => 'Public Hearing',
                                'stakeholder_forum' => 'Stakeholder Forum',
                                'workshop' => 'Workshop',
                                'conference' => 'Conference',
                                'seminar' => 'Seminar',
                                'webinar' => 'Webinar',
                            ])
                            ->required(),

                        Grid::make(2)
                            ->schema([
                                DateTimePicker::make('start_date')
                                    ->required()
                                    ->native(false),

                                DateTimePicker::make('end_date')
                                    ->required()
                                    ->native(false),
                            ]),

                        TextInput::make('location')
                            ->required()
                            ->maxLength(255),

                        TextInput::make('supporters')
                            ->numeric()
                            ->default(0),

                        TextInput::make('max_attendees')
                            ->numeric()
                            ->label('Max Attendees')
                            ->default(0),

                        Toggle::make('is_published')
                            ->label('Publish this Event')
                            ->helperText('Enable to make this event visible to the public')
                            ->onColor('success')
                            ->offColor('secondary')
                            ->default(false),
                    ]),

                Section::make('Event Media')
                    ->columns(2)
                    ->schema([
                        FileUpload::make('image_path')
                            ->label('Featured Image')
                            ->directory('events')
                            ->image()
                            ->imageEditor()
                            ->maxSize(2048)
                            ->columnSpan(1),

                        FileUpload::make('gallery')
                            ->label('Gallery Images')
                            ->directory('events/gallery')
                            ->image()
                            ->multiple()
                            ->maxSize(2048)
                            ->columnSpan(1),
                    ]),

                Section::make('Additional Information')
                    ->columns(2)
                    ->schema([
                        Textarea::make('location_details')
                            ->label('Location Details')
                            ->rows(3)
                            ->helperText('Detailed directions or room information')
                            ->columnSpanFull(),

                        TextInput::make('organizer')
                            ->label('Organizer')
                            ->maxLength(100),

                        TextInput::make('organizer_contact')
                            ->label('Organizer Contact')
                            ->maxLength(100),

                        TextInput::make('registration_link')
                            ->label('Registration Link')
                            ->url(),
                    ]),

                Section::make('Event Agenda')
                    ->schema([
                        Repeater::make('agenda')
                            ->schema([
                                TextInput::make('time')
                                    ->label('Time')
                                    ->required()
                                    ->maxLength(20),

                                TextInput::make('activity')
                                    ->label('Activity')
                                    ->required()
                                    ->maxLength(100),

                                TextInput::make('duration')
                                    ->label('Duration')
                                    ->maxLength(20),

                                TextInput::make('speaker')
                                    ->label('Speaker')
                                    ->maxLength(100),
                            ])
                            ->columns(4)
                            ->itemLabel(fn(array $state): ?string => $state['time'] . ' - ' . $state['activity'] ?? null)
                            ->collapsible()
                            ->collapsed()
                            ->defaultItems(0),
                    ])
                    ->collapsible()
                    ->collapsed(),

                // Fixed Event Speakers section
                Section::make('Event Speakers')
                    ->schema([
                        Repeater::make('speakers')
                            ->schema([
                                TextInput::make('name')
                                    ->label('Name')
                                    ->required()
                                    ->maxLength(100),

                                TextInput::make('title')
                                    ->label('Title/Position')
                                    ->maxLength(100),

                                Textarea::make('bio')
                                    ->label('Biography')
                                    ->rows(2)
                                    ->maxLength(500),

                                FileUpload::make('photo')
                                    ->label('Photo')
                                    ->directory('events/speakers')
                                    ->image()
                                    ->maxSize(1024),
                            ])
                            ->columns(2)
                            ->itemLabel(fn(array $state): ?string => $state['name'] ?? null)
                            ->collapsible()
                            ->collapsed()
                            ->defaultItems(0),
                    ])
                    ->collapsible()
                    ->collapsed(),
            ]);
    }

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

                BadgeColumn::make('event_type')
                    ->formatStateUsing(fn($state) => ucfirst(str_replace('_', ' ', $state)))
                    ->colors([
                        'public_hearing' => 'primary',
                        'stakeholder_forum' => 'success',
                        'workshop' => 'warning',
                        'conference' => 'danger',
                        'seminar' => 'info',
                        'webinar' => 'indigo',
                    ])
                    ->sortable(),

                TextColumn::make('start_date')
                    ->dateTime('M d, Y g:i A')
                    ->sortable(),

                TextColumn::make('location')
                    ->searchable()
                    ->limit(20),

                TextColumn::make('supporters')
                    ->sortable()
                    ->label('Supporters')
                    ->alignCenter(),

                TextColumn::make('registrations_count')
                    ->counts('registrations')
                    ->sortable()
                    ->label('Registrations')
                    ->alignCenter(),

                IconColumn::make('is_published')
                    ->boolean()
                    ->sortable()
                    ->label('Published')
                    ->alignCenter(),
            ])
            ->filters([
                SelectFilter::make('event_type')
                    ->options([
                        'public_hearing' => 'Public Hearing',
                        'stakeholder_forum' => 'Stakeholder Forum',
                        'workshop' => 'Workshop',
                        'conference' => 'Conference',
                        'seminar' => 'Seminar',
                        'webinar' => 'Webinar',
                    ]),

                SelectFilter::make('is_published')
                    ->options([
                        '1' => 'Published',
                        '0' => 'Unpublished',
                    ])
                    ->label('Publication Status'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('start_date', 'desc')
            ->groups([
                Tables\Grouping\Group::make('start_date')
                    ->label('By Date')
                    ->date()
                    ->collapsible(),

                Tables\Grouping\Group::make('event_type')
                    ->label('By Type')
                    ->collapsible(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            \App\Filament\Resources\EventResource\RelationManagers\RegistrationsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListEvents::route('/'),
            'create' => Pages\CreateEvent::route('/create'),
            'edit' => Pages\EditEvent::route('/{record}/edit'),
            'view' => Pages\ViewEvent::route('/{record}'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('start_date', '>', now())->count();
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'primary';
    }
}
