<?php

namespace App\Filament\Resources\VehicleResource\RelationManagers;

use App\Models\VehicleMaintenanceLog;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;

class MaintenanceLogsRelationManager extends RelationManager
{
    protected static string $relationship = 'maintenanceLogs';

    protected static ?string $title = 'Maintenance';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Maintenance details')
                    ->columns(2)
                    ->schema([
                        Forms\Components\Select::make('type')
                            ->label('Type')
                            ->required()
                            ->options(VehicleMaintenanceLog::types()),

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

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

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

                        // 👇 Show dollars in the UI, store cents in DB (using cost_cents)
                        Forms\Components\TextInput::make('cost_cents')
                            ->label('Total cost')
                            ->prefix('$')
                            ->numeric()
                            ->minValue(0)
                            ->nullable()
                            ->afterStateHydrated(function (
                                Forms\Components\TextInput $component,
                                $state
                            ): void {
                                // Convert stored cents → dollars for display
                                if ($state !== null) {
                                    $component->state($state / 100);
                                }
                            })
                            ->dehydrateStateUsing(function ($state): ?int {
                                // Convert entered dollars → cents for storage
                                if ($state === null || $state === '') {
                                    return null;
                                }

                                return (int) round(((float) $state) * 100);
                            })
                            ->helperText('Enter amount in dollars, e.g. 350.00 (stored as cents).'),

                        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')
                            ->required()
                            ->native(false)
                            ->closeOnDateSelection(),

                        Forms\Components\DatePicker::make('next_due_at')
                            ->label('Next due')
                            ->native(false)
                            ->closeOnDateSelection()
                            ->helperText('Next service / COF due date'),

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

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('title')
            ->columns([
                Tables\Columns\TextColumn::make('performed_at')
                    ->label('Performed on')
                    ->date()
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('title')
                    ->limit(40)
                    ->searchable(),

                Tables\Columns\TextColumn::make('odometer_km')
                    ->label('Odometer (km)')
                    ->sortable(),

                Tables\Columns\TextColumn::make('next_due_at')
                    ->label('Next due')
                    ->date()
                    ->sortable(),

                Tables\Columns\TextColumn::make('cost_cents')
                    ->label('Total cost')
                    ->formatStateUsing(function ($state): string {
                        if ($state === null) {
                            return '—';
                        }

                        return '$' . number_format($state / 100, 2);
                    })
                    ->sortable(),

                Tables\Columns\IconColumn::make('charge_owner')
                    ->label('Charged to owner')
                    ->boolean(),
            ])
            ->defaultSort('performed_at', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->options(VehicleMaintenanceLog::types()),

                Tables\Filters\TernaryFilter::make('charge_owner')
                    ->label('Charged to owner'),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('New vehicle maintenance log'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }
}
