<?php

declare(strict_types=1);

namespace App\Filament\Resources;

use App\Filament\Resources\VehicleMaintenanceLogResource\Pages;
use App\Models\VehicleMaintenanceLog;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Carbon;

class VehicleMaintenanceLogResource extends Resource
{
    protected static ?string $model = VehicleMaintenanceLog::class;

    protected static ?string $navigationIcon  = 'heroicon-o-wrench';
    protected static ?string $navigationGroup = 'Fleet';
    protected static ?string $navigationLabel = 'Vehicle Maintenance';
    protected static ?int    $navigationSort  = 3; // under Vehicles / Owners

    public static function getModelLabel(): string
    {
        return 'Maintenance Log';
    }

    public static function getPluralModelLabel(): string
    {
        return 'Maintenance Logs';
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Maintenance details')
                    ->columns(2)
                    ->schema([
                        Forms\Components\Select::make('vehicle_id')
                            ->label('Vehicle')
                            ->relationship('vehicle', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            // Allow widget / URL to pre-select the vehicle
                            ->default(fn () => request()->get('vehicle_id')),

                        Forms\Components\Select::make('type')
                            ->label('Type')
                            ->options(VehicleMaintenanceLog::types())
                            ->required()
                            // Allow widget / URL to pre-select the type (cof|rego|service)
                            ->default(fn () => request()->get('type')),

                        Forms\Components\TextInput::make('title')
                            ->label('Title')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\TextInput::make('odometer_km')
                            ->label('Odometer (km)')
                            ->numeric()
                            ->nullable(),

                        // Only show this for Service logs
                        Forms\Components\TextInput::make('next_service_due_km')
                            ->label('Next service due at (km)')
                            ->numeric()
                            ->minValue(0)
                            ->helperText('Sets the vehicle’s "Next service due (km)" value.')
                            ->nullable()
                            ->visible(fn (Get $get) => strtolower((string) $get('type')) === 'service'),

                        // Money in DOLLARS in the UI, stored as cents in DB.
                        Forms\Components\TextInput::make('cost_cents')
                            ->label('Total cost ($)')
                            ->prefix('$')
                            ->numeric()
                            ->helperText('Enter dollars, e.g. 350.00')
                            // Show DB cents value as dollars in the input
                            ->formatStateUsing(function ($state) {
                                if ($state === null) {
                                    return null;
                                }

                                return number_format(((int) $state) / 100, 2, '.', '');
                            })
                            // Convert dollars typed by user back to cents for saving
                            ->dehydrateStateUsing(function ($state) {
                                if ($state === null || $state === '') {
                                    return null;
                                }

                                $normalized = preg_replace('/[^\d.]/', '', (string) $state);

                                return (int) round(((float) $normalized) * 100);
                            })
                            ->nullable(),

                        Forms\Components\Toggle::make('charge_owner')
                            ->label('Charge cost to owner')
                            ->helperText('If on, and this is a consignment vehicle, the cost will appear in the owner ledger.')
                            ->default(false),

                        Forms\Components\DatePicker::make('performed_at')
                            ->label('Performed on')
                            ->native(false)
                            ->closeOnDateSelection()
                            ->required()
                            // Default to "today" if not set, but don't override existing value on edit
                            ->default(fn (?string $state) => $state ?: Carbon::today()->toDateString()),

                        // Only show this for non-Service logs (COF / Rego / etc)
                        Forms\Components\DatePicker::make('next_due_at')
                            ->label('Next due')
                            ->native(false)
                            ->closeOnDateSelection()
                            ->helperText('Next COF / rego / other due date. Updates the vehicle record for this type.')
                            ->nullable()
                            ->visible(fn (Get $get) => strtolower((string) $get('type')) !== 'service')
                            // Default from query if present (widget will send cof_due_at / rego_due_at)
                            ->default(function (Get $get, ?string $state) {
                                if ($state) {
                                    return $state;
                                }

                                $type = strtolower((string) $get('type'));

                                // Widget sends one of these for COF/rego
                                $fromUrl = null;
                                if ($type === 'cof') {
                                    $fromUrl = request()->get('cof_due_at');
                                } elseif ($type === 'rego') {
                                    $fromUrl = request()->get('rego_due_at');
                                }

                                // If URL param exists, use it; otherwise fall back to +6 months
                                if ($fromUrl) {
                                    return $fromUrl;
                                }

                                if (in_array($type, ['cof', 'rego'], true)) {
                                    return Carbon::today()->addMonthsNoOverflow(6)->toDateString();
                                }

                                return null;
                            }),

                        Forms\Components\Textarea::make('description')
                            ->label('Description')
                            ->columnSpanFull()
                            ->rows(3),

                        Forms\Components\FileUpload::make('attachment_path')
                            ->label('Attachment (invoice / COF)')
                            ->directory('maintenance')
                            ->maxSize(10_240)
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('vehicle.name')
                    ->label('Vehicle')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('type')
                    ->label('Type')
                    ->formatStateUsing(fn (string $state) => VehicleMaintenanceLog::types()[$state] ?? $state)
                    ->sortable(),

                Tables\Columns\TextColumn::make('title')
                    ->label('Title')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('performed_at')
                    ->label('Performed on')
                    ->date('d M Y')
                    ->sortable(),

                Tables\Columns\TextColumn::make('next_due_at')
                    ->label('Next due')
                    ->date('d M Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('next_service_due_km')
                    ->label('Next service km')
                    ->numeric()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('odometer_km')
                    ->label('Odo (km)')
                    ->numeric()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('cost_cents')
                    ->label('Cost')
                    ->formatStateUsing(
                        fn ($state) => $state !== null
                            ? '$' . number_format($state / 100, 2)
                            : '—'
                    )
                    ->sortable(),

                Tables\Columns\IconColumn::make('charge_owner')
                    ->label('Charged to owner')
                    ->boolean(),
            ])
            ->defaultSort('performed_at', 'desc')
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListVehicleMaintenanceLogs::route('/'),
            'create' => Pages\CreateVehicleMaintenanceLog::route('/create'),
            'edit'   => Pages\EditVehicleMaintenanceLog::route('/{record}/edit'),
        ];
    }
}
