<?php

declare(strict_types=1);

namespace App\Filament\Resources\JobResource\Pages;

use App\Filament\Resources\JobResource;
use App\Services\JobImportService;
use App\Services\VevsClientFactory;
use Filament\Actions;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;

class ListJobs extends ListRecords
{
    protected static string $resource = JobResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\CreateAction::make(),

            Actions\Action::make('importFromVevs')
                ->label('Import from VEVS')
                ->icon('heroicon-o-cloud-arrow-down')
                ->modalHeading('Import reservation from VEVS')
                ->modalSubmitActionLabel('Import')
                ->form([
                    Forms\Components\TextInput::make('reference')
                        ->label('Reservation reference')
                        ->required()
                        ->placeholder('e.g. RR1736197027'),

                    Forms\Components\Select::make('brand')
                        ->label('Brand')
                        ->required()
                        ->options([
                            'jimny'       => 'Jimny Rentals',
                            'dreamdrives' => 'Dream Drives',
                        ])
                        ->default('jimny'),
                ])
                ->action(function (array $data, VevsClientFactory $factory, JobImportService $importer): void {
                    $ref   = (string) $data['reference'];
                    $brand = (string) $data['brand'];

                    $client  = $factory->forBrandKey($brand);
                    $payload = $client->fetchReservationByRef($ref);

                    if (! $payload) {
                        Notification::make()
                            ->danger()
                            ->title('Import failed')
                            ->body("No reservation found in VEVS for [{$ref}] on [{$brand}].")
                            ->send();

                        return;
                    }

                    // Dream Drives: { status, code, data: {...} }
                    $booking = $payload['data'] ?? $payload;

                    $job = $importer->importFromVevsPayload($booking, $brand);

                    Notification::make()
                        ->success()
                        ->title('Reservation imported')
                        ->body("Job #{$job->id} ({$brand}) imported/updated from VEVS reference {$ref}.")
                        ->send();

                    // Jump straight to the job view page
                    $this->redirect(
                        JobResource::getUrl('view', ['record' => $job])
                    );
                }),
        ];
    }
}
