<?php

namespace App\Filament\Resources;

use App\Filament\Resources\NotificationTemplateResource\Pages;
use App\Models\NotificationTemplate;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class NotificationTemplateResource extends Resource
{
    protected static ?string $model = NotificationTemplate::class;

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

    protected static ?string $navigationLabel = 'Templates';

    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Template Details')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->maxLength(255)
                            ->live(onBlur: true)
                            ->afterStateUpdated(fn (Forms\Set $set, ?string $state) => 
                                $set('key', NotificationTemplate::generateKey($state ?? ''))),
                                
                        Forms\Components\TextInput::make('key')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(255)
                            ->hint('Unique identifier for programmatic use'),
                            
                        Forms\Components\Textarea::make('description')
                            ->rows(2)
                            ->hint('Optional description of when to use this template'),
                            
                        Forms\Components\Toggle::make('is_active')
                            ->default(true)
                            ->label('Active'),
                    ])
                    ->columns(2),
                    
                Forms\Components\Section::make('Message Content')
                    ->schema([
                        Forms\Components\Textarea::make('message')
                            ->required()
                            ->rows(6)
                            ->hint('Use {{variable_name}} for dynamic content')
                            ->columnSpanFull(),
                            
                        Forms\Components\TagsInput::make('variables')
                            ->label('Template Variables')
                            ->hint('Variables that can be replaced in the message')
                            ->columnSpanFull(),
                    ]),
                    
                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'),
                    ])
                    ->collapsed(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                    
                Tables\Columns\TextColumn::make('key')
                    ->searchable()
                    ->sortable()
                    ->copyable()
                    ->copyMessage('Template key copied')
                    ->copyMessageDuration(1500),
                    
                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->label('Active'),
                    
                Tables\Columns\TextColumn::make('message')
                    ->limit(50)
                    ->tooltip(function (TextColumn $column): ?string {
                        $state = $column->getState();
                        if (strlen($state) <= 50) {
                            return null;
                        }
                        return $state;
                    }),
                    
                Tables\Columns\TagsColumn::make('variables')
                    ->label('Variables')
                    ->separator(','),
                    
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                    
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active Templates')
                    ->boolean()
                    ->trueLabel('Only active templates')
                    ->falseLabel('Only inactive templates')
                    ->native(false),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
                
                Tables\Actions\Action::make('test_send')
                    ->label('Test Send')
                    ->icon('heroicon-o-paper-airplane')
                    ->color('primary')
                    ->form([
                        Forms\Components\Select::make('user_id')
                            ->label('Test User')
                            ->options(fn () => \App\Models\User::limit(20)->pluck('name', 'id'))
                            ->searchable()
                            ->required(),
                        Forms\Components\KeyValue::make('variables')
                            ->label('Test Variables')
                            ->keyLabel('Variable Name')
                            ->valueLabel('Test Value'),
                    ])
                    ->action(function (NotificationTemplate $record, array $data) {
                        try {
                            $service = app(\App\Services\Notification\NotificationService::class);
                            $results = $service->sendTemplate(
                                $record->key, 
                                [$data['user_id']], 
                                $data['variables'] ?? []
                            );
                            
                            if ($results[0]['success']) {
                                \Filament\Notifications\Notification::make()
                                    ->title('Test message sent successfully!')
                                    ->success()
                                    ->send();
                            } else {
                                \Filament\Notifications\Notification::make()
                                    ->title('Failed to send test message')
                                    ->body($results[0]['error'])
                                    ->danger()
                                    ->send();
                            }
                        } catch (\Exception $e) {
                            \Filament\Notifications\Notification::make()
                                ->title('Error sending test message')
                                ->body($e->getMessage())
                                ->danger()
                                ->send();
                        }
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListNotificationTemplates::route('/'),
            'create' => Pages\CreateNotificationTemplate::route('/create'),
            'view' => Pages\ViewNotificationTemplate::route('/{record}'),
            'edit' => Pages\EditNotificationTemplate::route('/{record}/edit'),
        ];
    }
}