<?php

namespace App\Filament\Resources\SupportConversations\Pages;

use App\Filament\Resources\SupportConversations\SupportConversationResource;
use App\Models\SupportMessage;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;

class ViewSupportConversation extends ViewRecord
{
    protected static string $resource = SupportConversationResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('reply')
                ->label('Reply in Admin')
                ->icon('heroicon-o-chat-bubble-left-right')
                ->color('primary')
                ->form([
                    Textarea::make('message')
                        ->label('Message to customer')
                        ->required()
                        ->rows(4),
                ])
                ->action(function (array $data) {
                    SupportMessage::create([
                        'support_conversation_id' => $this->record->id,
                        'sender_type' => 'staff',
                        'message' => $data['message'],
                    ]);

                    $this->record->update(['status' => 'open']);

                    Notification::make()
                        ->title('Reply sent.')
                        ->success()
                        ->send();

                    return redirect(static::getResource()::getUrl('view', ['record' => $this->record]));
                }),

            \Filament\Actions\Action::make('Connect on WhatsApp')
                ->icon('heroicon-o-chat-bubble-left')
                ->color('success')
                ->url(fn ($record) => "https://wa.me/" . preg_replace('/[^0-9]/', '', $record->email_phone) . "?text=" . urlencode("Hi " . $record->name . ", we received your request regarding " . $record->subject_service . "."))
                ->openUrlInNewTab(),

            \Filament\Actions\Action::make('Connect on Telegram')
                ->icon('heroicon-o-paper-airplane')
                ->color('info')
                ->url(fn ($record) => "https://t.me/" . $record->email_phone)
                ->openUrlInNewTab(),

            EditAction::make(),
        ];
    }
}
