<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ContractResource\Pages;
use App\Models\Contract;
use App\Models\Driver;
use App\Services\ContractValidator;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Str;

class ContractResource extends Resource
{
    protected static ?string $model = Contract::class;
    protected static ?string $navigationIcon = 'heroicon-o-document-text';
    protected static ?string $navigationGroup = 'RentX';

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Ugovor')->schema([
                Forms\Components\TextInput::make('number')
                    ->label('Broj ugovora')
                    ->required()
                    ->default(fn () => 'UG-' . now()->format('Ymd') . '-' . Str::upper(Str::random(4)))
                    ->maxLength(50),

                Forms\Components\Select::make('vehicle_id')->label('Vozilo')
                    ->relationship('vehicle', 'registration')->searchable()->required(),

                Forms\Components\Select::make('driver_id')->label('Vozač')
                    ->relationship('driver', 'first_name')
                    ->getOptionLabelFromRecordUsing(fn (Driver $r) => $r->full_name . ($r->oib ? ' • '.$r->oib : ''))
                    ->searchable()
                    ->required(),

                Forms\Components\DateTimePicker::make('date_from')->label('Od')->required(),
                Forms\Components\DateTimePicker::make('date_to')->label('Do')->required(),

                Forms\Components\TextInput::make('price')->label('Cijena')->numeric()->required()->default(0),
                Forms\Components\TextInput::make('deposit')->label('Depozit')->numeric()->default(0),

                Forms\Components\TextInput::make('included_km')->label('Uključeni km')->numeric(),
                Forms\Components\TextInput::make('extra_km_rate')->label('Cijena po dodatnom km')->numeric(),

                Forms\Components\Select::make('status')->label('Status')->options([
                    'active' => 'Aktivan',
                    'closed' => 'Završen',
                    'canceled' => 'Otkazan',
                ])->required()->default('active'),

                Forms\Components\Textarea::make('notes')->label('Napomena')->columnSpanFull(),
            ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('number')->label('Broj')->searchable(),
                Tables\Columns\TextColumn::make('vehicle.registration')->label('Vozilo')->searchable(),
                Tables\Columns\TextColumn::make('driver.full_name')->label('Vozač')->searchable(['drivers.first_name','drivers.last_name']),
                Tables\Columns\TextColumn::make('date_from')->label('Od')->dateTime()->sortable(),
                Tables\Columns\TextColumn::make('date_to')->label('Do')->dateTime()->sortable(),
                Tables\Columns\TextColumn::make('price')->label('Cijena')->money('EUR'),
                Tables\Columns\TextColumn::make('status')->label('Status')->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')->label('Status')->options([
                    'active' => 'Aktivan', 'closed' => 'Završen', 'canceled' => 'Otkazan',
                ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ]);
    }

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

    public static function validateDriverOrFail(int $driverId): void
    {
        $driver = Driver::findOrFail($driverId);

        $validator = app(ContractValidator::class);
        $errors = $validator->validateDriver($driver);

        if (!empty($errors)) {
            throw new \Exception(implode(' ', $errors));
        }
    }
}
