<?php

namespace Modules\Booking\Filament\Resources\Bookings\Actions;

use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Modules\Booking\Actions\AssignDriverAction;
use Modules\Booking\Data\AssignDriverData;
use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Exceptions\DriverAssignmentNotAllowedException;
use Modules\Booking\Models\Booking;

/**
 * Shared between BookingsTable (row action) and ViewBooking (header action)
 * so both surfaces stay in sync — one definition, not two.
 */
class AssignDriverTableAction
{
    public static function make(): Action
    {
        return Action::make('assignDriver')
            ->label('Assign Driver')
            ->icon(Heroicon::OutlinedTruck)
            ->color('primary')
            ->visible(fn (Booking $record): bool => $record->status === BookingStatus::Confirmed
                && $record->travel_date->gte(today())
                && (auth()->user()?->can('manage_bookings') ?? false))
            ->schema([
                TextInput::make('driver_name')->required(),
                TextInput::make('driver_phone')->required(),
                TextInput::make('car_plate_number')->required(),
                TextInput::make('car_model'),
            ])
            ->fillForm(fn (Booking $record): array => [
                'driver_name' => $record->driver_name,
                'driver_phone' => $record->driver_phone,
                'car_plate_number' => $record->car_plate_number,
                'car_model' => $record->car_model,
            ])
            ->action(function (array $data, Booking $record, AssignDriverAction $assignDriverAction) {
                try {
                    $assignDriverAction->handle($record, new AssignDriverData(
                        driverName: $data['driver_name'],
                        driverPhone: $data['driver_phone'],
                        carPlateNumber: $data['car_plate_number'],
                        carModel: $data['car_model'] ?: null,
                    ));

                    Notification::make()
                        ->title('Driver assigned')
                        ->success()
                        ->send();
                } catch (DriverAssignmentNotAllowedException $exception) {
                    Notification::make()
                        ->title('Cannot assign driver')
                        ->body($exception->getMessage())
                        ->danger()
                        ->send();
                }
            });
    }
}
