<?php

namespace App\Filament\Resources\Monitoring\MediaMonitorings\Actions;

use App\Filament\Support\CheerfulNotification;
use App\Models\Theme;
use App\Services\NewsCrawlerService;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;

class CrawlNewsAction extends Action
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Crawl Berita')
            ->color('slate')
            ->schema([
                TextInput::make('keyword')
                    ->label('Kata Kunci')
                    ->placeholder('Pendidikan, UMKM, Pariwisata')
                    ->autocomplete(false)
                    ->autofocus()
                    ->required()
                    ->helperText('Jika kata kunci nya lebih dari 1, pisahkan dengan koma.'),

                Select::make('theme_id')
                    ->label('Tema')
                    ->required()
                    ->options(Theme::active()->pluck('name', 'id'))
                    ->searchable()
                    ->multiple(),

                TextInput::make('limit')
                    ->label('Jumlah Berita')
                    ->placeholder(10)
                    ->numeric()
                    ->required()
                    ->default(10)
                    ->autocomplete(false),
            ])
            ->action(function (array $data, NewsCrawlerService $service): void {
                $count = $service->crawlFromGoogleNews($data['keyword'], $data['limit'], (array) ($data['theme_id'] ?? []));

                if ($count > 0) {
                    CheerfulNotification::success(
                        'Crawl Berhasil! 🕸️🚀',
                        "Mantap! Ada {$count} berita baru nih tentang '{$data['keyword']}' di Purwakarta. Databasenya makin kaya! 😎"
                    )->send();
                } else {
                    CheerfulNotification::info(
                        'Belum Ada Berita Baru 🔍',
                        "Hmm, sepertinya belum ada update berita baru untuk '{$data['keyword']}'. Coba lagi nanti ya! 😉"
                    )->send();
                }
            })
            ->modalWidth(Width::Large);
    }
}
