<?php

namespace App\Filament\Pages;

use App\Models\User;
use App\Notifications\PromotionNotification;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification as FilamentNotification;
use Kreait\Firebase\Messaging\CloudMessage;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Log;

class SendPromotions extends Page implements HasForms
{
    use InteractsWithForms;

    protected static ?string $navigationIcon = 'heroicon-o-paper-airplane';

    protected static string $view = 'filament.pages.send-promotions';

    public static function getNavigationLabel(): string
    {
        return __('Send Promotions');
    }

    public static function getNavigationGroup(): string
    {
        return __('Send Promotions');
    }

    public function getTitle(): string
    {
        return __('Send Promotion');
    }

    public $title_ar;
    public $title_en;
    public $body_ar;
    public $body_en;

    protected function getFormSchema(): array
    {
        return [
            TextInput::make('title_ar')->label(__('Arabic Title'))->required(),
            TextInput::make('title_en')->label(__('English Title'))->required(),
            Textarea::make('body_ar')->label(__('Arabic Description')),
            Textarea::make('body_en')->label(__('English Description')),
        ];
    }

    public function send()
    {
        $this->validate();

        // $ar_notification = new PromotionNotification($this->title_ar, $this->body_ar);
        // $en_notification = new PromotionNotification($this->title_en, $this->body_en);
        // // Send to topics
        // Notification::route('fcm', 'promotions_ar')
        //     ->notify($ar_notification);
        // Notification::route('fcm', 'promotions_en')
        //     ->notify($en_notification);
        $messaging = app('firebase.messaging');

        $global_notification_ar = CloudMessage::new()
            ->toTopic('promotions_ar')
            ->withNotification(
                \Kreait\Firebase\Messaging\Notification::create($this->title_ar, $this->body_ar)
            );
        $global_notification_en = CloudMessage::new()
            ->toTopic('promotions_en')
            ->withNotification(
                \Kreait\Firebase\Messaging\Notification::create($this->title_en, $this->body_en)
            );
        try {
            foreach ([$global_notification_ar, $global_notification_en] as $notification) {
                Log::info("message result", $notification->jsonSerialize());
                $result = $messaging->send($notification);
                Log::info("message result", $result);
            }
        } catch (\Exception $e) {
            Log::error('Promotion sending failed: ' . $e->getMessage());
            FilamentNotification::make()
                ->title(__('Error sending promotions'))
                ->danger()
                ->send();
        }

        // Save to database for all users for in-app notifications
        // $users = User::all();
        $notifications = [];

        // foreach ($users as $user) {
        //     $lang = $user->pref_lang ?? 'ar';
        //     $title = $this->{'title_' . $lang};
        //     $desc = $this->{'desc_' . $lang};

        //     $notifications[] = [
        //         'id' => \Illuminate\Support\Str::uuid()->toString(),
        //         'notifiable_type' => User::class,
        //         'notifiable_id' => $user->id,
        //         'type' => PromotionNotification::class,
        //         'data' => json_encode(['title' => $title, 'body' => $desc]),
        //     ];
        // }
        $notifications[] = [
            'id' => \Illuminate\Support\Str::uuid()->toString(),
            'notifiable_type' => User::class,
            'notifiable_id' => User::first()->id,
            'type' => PromotionNotification::class,
            'data' => json_encode([
                'title_ar' => $this->title_ar,
                'body_ar' => $this->body_ar,
                'title_en' => $this->title_en,
                'body_en' => $this->body_en
            ]),
            'created_at' => now()
        ];

        try {
            // Insert all notifications in a single query for efficiency
            \Illuminate\Support\Facades\DB::table('notifications')->insert($notifications);

            FilamentNotification::make()
                ->title(__('Promotions sent successfully'))
                ->success()
                ->send();

            $this->reset();
        } catch (\Exception $e) {
            Log::error('Promotion sending failed: ' . $e->getMessage());
            FilamentNotification::make()
                ->title(__('Error sending promotions'))
                ->danger()
                ->send();
        }
    }
}
