<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SupportChatResource\Pages;
use App\Models\SupportChat;
use App\Models\SupportMessage;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class SupportChatResource extends Resource
{
    protected static ?string $model = SupportChat::class;

    protected static ?string $navigationIcon = 'heroicon-o-chat-bubble-left-right';

    protected static ?string $navigationLabel = 'Chat de Soporte';

    protected static ?string $modelLabel = 'Chat de Soporte';

    protected static ?string $pluralModelLabel = 'Chats de Soporte';

    protected static ?int $navigationSort = 4;

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Usuario')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('user.email')
                    ->label('Correo')
                    ->searchable(),

                Tables\Columns\TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'open' => 'success',
                        'closed' => 'gray',
                        default => 'warning',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'open' => 'Abierto / En línea',
                        'closed' => 'Cerrado',
                        default => $state,
                    }),

                Tables\Columns\TextColumn::make('latestMessage.message')
                    ->label('Último Mensaje')
                    ->limit(50),

                Tables\Columns\TextColumn::make('last_message_at')
                    ->label('Última Actividad')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->defaultSort('last_message_at', 'desc')
            ->actions([
                Tables\Actions\Action::make('reply')
                    ->label('Responder Chat')
                    ->icon('heroicon-o-chat-bubble-bottom-center-text')
                    ->color('primary')
                    ->modalHeading(fn (SupportChat $record) => "Atención a Cliente: {$record->user->name}")
                    ->modalWidth('2xl')
                    ->modalContent(fn (SupportChat $record) => view('filament.resources.support_chat.chat_thread', ['record' => $record]))
                    ->form([
                        Forms\Components\Textarea::make('reply_message')
                            ->label('Respuesta del Agente')
                            ->required()
                            ->rows(3)
                            ->placeholder('Escribe tu respuesta al usuario...'),
                    ])
                    ->modalSubmitActionLabel('Enviar Mensaje')
                    ->action(function (SupportChat $record, array $data) {
                        $agent = auth()->user();
                        $replyText = trim($data['reply_message']);

                        $message = $record->messages()->create([
                            'sender_id' => $agent ? $agent->id : null,
                            'sender_type' => 'agent',
                            'message' => $replyText,
                            'is_read' => false,
                        ]);

                        $record->update(['last_message_at' => now()]);

                        // Notificación Push al cliente
                        if ($record->user) {
                            try {
                                \App\Services\FcmService::sendNotification(
                                    $record->user,
                                    'Soporte Wincar 💬',
                                    "Tienes un nuevo mensaje del equipo de soporte Wincar."
                                );
                            } catch (\Exception $e) {}
                        }

                        \Filament\Notifications\Notification::make()
                            ->title('Mensaje Enviado')
                            ->body("Tu respuesta fue enviada a {$record->user->name}")
                            ->success()
                            ->send();
                    }),
            ]);
    }

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