<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BroadcastCampaignResource\Pages;
use App\Models\BroadcastCampaign;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Filament\Infolists;
use Filament\Infolists\Infolist;

class BroadcastCampaignResource extends Resource
{
    protected static ?string $model = BroadcastCampaign::class;

    protected static ?string $navigationIcon = 'heroicon-o-megaphone';
    
    protected static ?string $navigationGroup = 'Notifications';

    protected static ?string $navigationLabel = 'Broadcast Campaigns';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Campaign Details')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->maxLength(255)
                            ->label('Campaign Name'),
                            
                        Forms\Components\Textarea::make('message')
                            ->required()
                            ->rows(4)
                            ->label('Message Content')
                            ->hint('Use {{name}}, {{first_name}}, {{user_id}} for personalization'),
                            
                        Forms\Components\Select::make('status')
                            ->options([
                                'draft' => 'Draft',
                                'scheduled' => 'Scheduled',
                                'sending' => 'Sending',
                                'sent' => 'Sent',
                                'paused' => 'Paused',
                                'cancelled' => 'Cancelled',
                            ])
                            ->default('draft')
                            ->required(),
                            
                        Forms\Components\DateTimePicker::make('scheduled_at')
                            ->label('Schedule For')
                            ->hint('Leave empty to send immediately'),
                    ])
                    ->columns(2),
                    
                Forms\Components\Section::make('Targeting')
                    ->schema([
                        Forms\Components\DateTimePicker::make('target_filters.active_since')
                            ->label('Active Since')
                            ->hint('Only send to users active since this date'),
                            
                        Forms\Components\DateTimePicker::make('target_filters.registered_since')
                            ->label('Registered Since')
                            ->hint('Only send to users registered since this date'),
                            
                        Forms\Components\TextInput::make('target_filters.exclude_recent_broadcast')
                            ->numeric()
                            ->label('Exclude Recent Broadcast (hours)')
                            ->hint('Don\'t send to users who received a broadcast within X hours')
                            ->default(24),
                    ])
                    ->columns(2),
                    
                Forms\Components\Section::make('Keyboard & Attachments')
                    ->schema([
                        Forms\Components\Repeater::make('inline_keyboard')
                            ->schema([
                                Forms\Components\Repeater::make('row')
                                    ->schema([
                                        Forms\Components\TextInput::make('text')
                                            ->required()
                                            ->label('Button Text'),
                                        Forms\Components\TextInput::make('callback_data')
                                            ->label('Callback Data'),
                                        Forms\Components\TextInput::make('url')
                                            ->url()
                                            ->label('URL'),
                                    ])
                                    ->columns(3)
                                    ->defaultItems(1)
                                    ->label('Buttons in this row'),
                            ])
                            ->label('Inline Keyboard')
                            ->hint('Create button rows for the message'),
                            
                        Forms\Components\Repeater::make('attachments')
                            ->schema([
                                Forms\Components\Select::make('type')
                                    ->options([
                                        'photo' => 'Photo',
                                        'document' => 'Document',
                                        'video' => 'Video',
                                    ])
                                    ->required(),
                                Forms\Components\TextInput::make('file_id')
                                    ->label('Telegram File ID')
                                    ->required(),
                                Forms\Components\TextInput::make('caption')
                                    ->label('Caption'),
                            ])
                            ->label('Attachments')
                            ->hint('Add media files to the broadcast'),
                    ])
                    ->collapsed(),
                    
                Forms\Components\Section::make('Settings')
                    ->schema([
                        Forms\Components\KeyValue::make('settings')
                            ->label('Additional Settings')
                            ->keyLabel('Setting Name')
                            ->valueLabel('Value'),
                    ])
                    ->collapsed(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                    
                Tables\Columns\BadgeColumn::make('status')
                    ->colors([
                        'secondary' => 'draft',
                        'primary' => 'scheduled',
                        'warning' => 'sending',
                        'success' => 'sent',
                        'danger' => 'cancelled',
                        'info' => 'paused',
                    ]),
                    
                Tables\Columns\TextColumn::make('total_recipients')
                    ->label('Recipients')
                    ->numeric()
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('sent_count')
                    ->label('Sent')
                    ->numeric()
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('failed_count')
                    ->label('Failed')
                    ->numeric()
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('progress')
                    ->label('Progress')
                    ->suffix('%')
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('creator.name')
                    ->label('Created By')
                    ->searchable(),
                    
                Tables\Columns\TextColumn::make('scheduled_at')
                    ->dateTime()
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'draft' => 'Draft',
                        'scheduled' => 'Scheduled',
                        'sending' => 'Sending',
                        'sent' => 'Sent',
                        'paused' => 'Paused',
                        'cancelled' => 'Cancelled',
                    ]),
                    
                Tables\Filters\Filter::make('scheduled')
                    ->query(fn (Builder $query): Builder => $query->whereNotNull('scheduled_at')),
                    
                Tables\Filters\DateFilter::make('created_at'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make()
                    ->visible(fn (BroadcastCampaign $record) => $record->isEditable()),
                    
                Tables\Actions\Action::make('send')
                    ->label('Send Now')
                    ->icon('heroicon-o-paper-airplane')
                    ->color('success')
                    ->visible(fn (BroadcastCampaign $record) => in_array($record->status, ['draft', 'scheduled', 'paused']))
                    ->requiresConfirmation()
                    ->action(function (BroadcastCampaign $record) {
                        app(\App\Services\Notification\NotificationService::class)->sendCampaign($record);
                    }),
                    
                Tables\Actions\Action::make('pause')
                    ->label('Pause')
                    ->icon('heroicon-o-pause')
                    ->color('warning')
                    ->visible(fn (BroadcastCampaign $record) => $record->status === 'sending')
                    ->requiresConfirmation()
                    ->action(function (BroadcastCampaign $record) {
                        $record->pause();
                    }),
                    
                Tables\Actions\Action::make('resume')
                    ->label('Resume')
                    ->icon('heroicon-o-play')
                    ->color('primary')
                    ->visible(fn (BroadcastCampaign $record) => $record->status === 'paused')
                    ->requiresConfirmation()
                    ->action(function (BroadcastCampaign $record) {
                        app(\App\Services\Notification\NotificationService::class)->resumeCampaign($record->id);
                    }),
                    
                Tables\Actions\Action::make('cancel')
                    ->label('Cancel')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (BroadcastCampaign $record) => !$record->isCompleted())
                    ->requiresConfirmation()
                    ->action(function (BroadcastCampaign $record) {
                        $record->cancel();
                    }),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make()
                    ->visible(fn () => auth()->user()->can('delete_broadcast_campaigns')),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make('Campaign Overview')
                    ->schema([
                        Infolists\Components\TextEntry::make('name')
                            ->label('Campaign Name'),
                        Infolists\Components\TextEntry::make('status')
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'draft' => 'gray',
                                'scheduled' => 'blue',
                                'sending' => 'orange',
                                'sent' => 'green',
                                'paused' => 'yellow',
                                'cancelled' => 'red',
                            }),
                        Infolists\Components\TextEntry::make('creator.name')
                            ->label('Created By'),
                        Infolists\Components\TextEntry::make('scheduled_at')
                            ->dateTime()
                            ->label('Scheduled For'),
                    ])
                    ->columns(2),
                    
                Infolists\Components\Section::make('Statistics')
                    ->schema([
                        Infolists\Components\TextEntry::make('total_recipients')
                            ->label('Total Recipients')
                            ->numeric(),
                        Infolists\Components\TextEntry::make('sent_count')
                            ->label('Successfully Sent')
                            ->numeric(),
                        Infolists\Components\TextEntry::make('failed_count')
                            ->label('Failed Deliveries')
                            ->numeric(),
                        Infolists\Components\TextEntry::make('progress')
                            ->label('Progress')
                            ->suffix('%'),
                        Infolists\Components\TextEntry::make('success_rate')
                            ->label('Success Rate')
                            ->suffix('%'),
                        Infolists\Components\TextEntry::make('estimated_completion')
                            ->label('Est. Completion')
                            ->dateTime(),
                    ])
                    ->columns(3),
                    
                Infolists\Components\Section::make('Message Content')
                    ->schema([
                        Infolists\Components\TextEntry::make('message')
                            ->label('Message')
                            ->markdown()
                            ->columnSpanFull(),
                    ]),
                    
                Infolists\Components\Section::make('Targeting & Settings')
                    ->schema([
                        Infolists\Components\KeyValueEntry::make('target_filters')
                            ->label('Target Filters'),
                        Infolists\Components\KeyValueEntry::make('settings')
                            ->label('Additional Settings'),
                    ])
                    ->columns(2)
                    ->collapsed(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBroadcastCampaigns::route('/'),
            'create' => Pages\CreateBroadcastCampaign::route('/create'),
            'view' => Pages\ViewBroadcastCampaign::route('/{record}'),
            'edit' => Pages\EditBroadcastCampaign::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['creator', 'recipients']);
    }
}