<?php

namespace App\Filament\Resources\Trips\Schemas;

use App\Models\Vehicle;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;

class TripForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([

                Section::make('Trip Details')
                    ->columns(2)
                    ->schema([
                        Select::make('driver_id')
                            ->label('Driver')
                            ->relationship('driver', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->columnSpan(1),

                        Select::make('vehicle_id')
                            ->label('Vehicle')
                            ->options(function (Get $get) {
                                $driverId = $get('driver_id');
                                if (!$driverId) {
                                    return Vehicle::all()->mapWithKeys(
                                        fn($v) => [$v->id => "{$v->color} {$v->make} {$v->model} — {$v->plate}"]
                                    );
                                }
                                return Vehicle::where('user_id', $driverId)->get()->mapWithKeys(
                                    fn($v) => [$v->id => "{$v->color} {$v->make} {$v->model} — {$v->plate}"]
                                );
                            })
                            ->searchable()
                            ->required()
                            ->helperText('Select driver first to filter their vehicles')
                            ->columnSpan(1),

                        Select::make('from_city_id')
                            ->label('Departing From')
                            ->relationship('fromCity', 'name_en')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->columnSpan(1),

                        Select::make('to_city_id')
                            ->label('Going To')
                            ->relationship('toCity', 'name_en')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->columnSpan(1),

                        DateTimePicker::make('departure_at')
                            ->label('Departure Date & Time')
                            ->required()
                            ->seconds(false)
                            ->columnSpan(1),

                        DateTimePicker::make('window_end')
                            ->label('Latest Departure (flexible window)')
                            ->helperText('Optional — e.g. driver departs between 6am–8am')
                            ->seconds(false)
                            ->columnSpan(1),
                    ]),

                Section::make('Seats & Pricing')
                    ->columns(3)
                    ->schema([
                        TextInput::make('seats_total')
                            ->label('Total Seats Available')
                            ->required()
                            ->numeric()
                            ->minValue(1)
                            ->maxValue(10)
                            ->live()
                            ->afterStateUpdated(fn($state, callable $set) => $set('seats_remaining', $state))
                            ->columnSpan(1),

                        TextInput::make('seats_remaining')
                            ->label('Seats Remaining')
                            ->helperText('Auto-set from total seats. Decreases as riders book.')
                            ->numeric()
                            ->minValue(0)
                            ->columnSpan(1),

                        TextInput::make('price_per_seat')
                            ->label('Price Per Seat (TZS)')
                            ->required()
                            ->numeric()
                            ->prefix('TZS')
                            ->minValue(0)
                            ->columnSpan(1),

                        TextInput::make('min_price_floor')
                            ->label('Corridor Minimum Price (TZS)')
                            ->helperText('Set automatically from the corridor. Do not change unless overriding.')
                            ->numeric()
                            ->prefix('TZS')
                            ->default(0)
                            ->columnSpan(1),
                    ]),

                Section::make('Pickup Location')
                    ->description('Click on the map to place the driver pickup pin. The coordinates are saved automatically.')
                    ->schema([
                        TextInput::make('pickup_note')
                            ->label('Pickup Description')
                            ->helperText('e.g. "Kariakoo bus stand, near Total petrol station"')
                            ->placeholder('Describe the pickup point clearly')
                            ->columnSpanFull(),

                        // Hidden coordinate fields — updated by the map below
                        TextInput::make('pickup_lat')
                            ->hidden()
                            ->dehydrated(true),

                        TextInput::make('pickup_lng')
                            ->hidden()
                            ->dehydrated(true),

                        // Interactive map pin picker
                        View::make('filament.forms.map-picker')
                            ->columnSpanFull(),
                    ]),

                Section::make('Status & Settings')
                    ->columns(2)
                    ->schema([
                        Select::make('status')
                            ->label('Trip Status')
                            ->options([
                                'draft'     => 'Draft (not yet visible)',
                                'live'      => 'Live (accepting bookings)',
                                'active'    => 'Active (driver en route)',
                                'completed' => 'Completed',
                                'cancelled' => 'Cancelled',
                            ])
                            ->default('live')
                            ->required()
                            ->columnSpan(1),

                        Toggle::make('is_promoted')
                            ->label('Promoted (appears at top of search)')
                            ->columnSpan(1),

                        Toggle::make('is_recurring')
                            ->label('Recurring weekly trip')
                            ->live()
                            ->columnSpan(1),

                        Select::make('recurrence_day')
                            ->label('Recurs every')
                            ->options([
                                0 => 'Sunday',
                                1 => 'Monday',
                                2 => 'Tuesday',
                                3 => 'Wednesday',
                                4 => 'Thursday',
                                5 => 'Friday',
                                6 => 'Saturday',
                            ])
                            ->visible(fn(Get $get) => (bool) $get('is_recurring'))
                            ->columnSpan(1),
                    ]),
            ]);
    }
}
