<?php

namespace App\Filament\Resources;

use App\Filament\Resources\VehicleResource\Pages;
use App\Filament\Resources\VehicleResource\RelationManagers;

use App\Models\Vehicle;
use App\Models\Country;
use App\Models\Employee;
use App\Models\InsuranceCompany;

use App\Enums\VehicleType;
use App\Enums\EuroNorm;
use App\Enums\FuelType;
use App\Enums\VehicleCertificateType;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Forms\Components\Actions\Action;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Resources\Pages\Page;
use Filament\Pages\SubNavigationPosition;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Enums\MaxWidth;

use Filament\Infolists;
use Filament\Infolists\Infolist;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Carbon;
use Illuminate\Contracts\View\View;
use Illuminate\Support\HtmlString;

use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Tables\Columns\SpatieMediaLibraryImageColumn;
use Filament\Infolists\Components\SpatieMediaLibraryImageEntry;

use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Actions\Tables\ExportBulkAction;

class VehicleResource extends Resource
{
    protected static ?string $model = Vehicle::class;

    protected static ?string $recordTitleAttribute = 'license_plate';

    protected static ?string $modelLabel = 'Araç';
    protected static ?string $pluralModelLabel = 'Araçlar';

    // protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationLabel = 'Araçlar';
    protected static ?string $navigationGroup = 'Uygulama';

    protected static ?int $navigationSort = 4;

    protected static int $globalSearchResultsLimit = 5;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Araç Bilgileri')
                    ->columns([
                        'lg' => 2,
                        'xl' => 4,
                    ])
                    ->icon('heroicon-m-truck')
                    ->schema([
                        //
                        Forms\Components\TextInput::make('license_plate')
                            ->label('Plaka')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\Select::make('country_id')
                            ->label('Plaka/Uyruk')
                            ->options(Country::all()->pluck('name', 'id'))
                            ->searchable()
                            ->default(222)
                            ->required(),

                        Forms\Components\TextInput::make('vin')
                            ->label('Şasi Numarası')
                            ->maxLength(255),

                        Forms\Components\Select::make('vehicle_type_id')
                            ->label('Araç Türü')
                            ->options(VehicleType::class)
                            ->searchable()
                            ->required()
                            ->live()
                            ->afterStateUpdated(function (Forms\Components\Select $component) {
                                $component
                                    ->getContainer()
                                    ->getComponent('dynamicVehicleFields')
                                    ->getChildComponentContainer()
                                    ->fill();
                            })
                            ->disabled(fn ($operation) => $operation === 'edit'),

                        Forms\Components\TextInput::make('make')
                            ->label('Marka')
                            ->maxLength(100),

                        Forms\Components\TextInput::make('model')
                            ->label('Model')
                            ->maxLength(100),

                        Forms\Components\TextInput::make('year')
                            ->label('Üretim Yılı')
                            ->maxLength(4),

                        Forms\Components\TextInput::make('color')
                            ->label('Renk')
                            ->maxLength(500),

                        Forms\Components\Grid::make(4)
                            ->schema(fn (Get $get): array => match ((string) $get('vehicle_type_id')) {
                                '1' => [
                                    // Binek Araç
                                    Forms\Components\Select::make('fuel_type_id')
                                        ->label('Yakıt Türü')
                                        ->options(FuelType::class)
                                        ->searchable()
                                        ->native(false),
                                ],
                                '2' => [
                                    // Çekici
                                    Forms\Components\Select::make('euro_norm_id')
                                        ->label('Avrupa Emisyon Standardı')
                                        ->options(EuroNorm::class)
                                        ->searchable()
                                        ->native(false),

                                    Forms\Components\ToggleButtons::make('has_adr_certificate')
                                        ->label('ADR sertifikası var mı?')
                                        ->boolean()
                                        ->grouped()
                                        ->default(false),
                                ],
                                '3' => [
                                    // Dorse
                                    Forms\Components\TextInput::make('length')
                                        ->label('Uzunluk (En)')
                                        ->placeholder('0.00')
                                        ->afterStateUpdated(function (Set $set, $state) {
                                            $state  = str_replace(',', '.', $state);
                                            $number = is_numeric($state) ? $state : 0;

                                            $set('length', number_format($number, 2, '.', ''));
                                        })
                                        ->rules(['decimal:2,4'])
                                        ->live(onBlur: true)
                                        ->suffix('metre'),

                                    Forms\Components\TextInput::make('width')
                                        ->label('Genişlik (Boy)')
                                        ->placeholder('0.00')
                                        ->afterStateUpdated(function (Set $set, $state) {
                                            $state  = str_replace(',', '.', $state);
                                            $number = is_numeric($state) ? $state : 0;

                                            $set('width', number_format($number, 2, '.', ''));
                                        })
                                        ->rules(['decimal:2,4'])
                                        ->live(onBlur: true)
                                        ->suffix('metre'),

                                    Forms\Components\TextInput::make('height')
                                        ->label('Yükseklik')
                                        ->placeholder('0.00')
                                        ->afterStateUpdated(function (Set $set, $state) {
                                            $state  = str_replace(',', '.', $state);
                                            $number = is_numeric($state) ? $state : 0;

                                            $set('height', number_format($number, 2, '.', ''));
                                        })
                                        ->rules(['decimal:2,4'])
                                        ->live(onBlur: true)
                                        ->suffix('metre'),

                                    Forms\Components\ToggleButtons::make('has_double_deck')
                                        ->label('Çift kat mı?')
                                        ->boolean()
                                        ->grouped()
                                        ->default(false),

                                    Forms\Components\ToggleButtons::make('has_partition')
                                        ->label('Ek bölme var mı?')
                                        ->boolean()
                                        ->grouped()
                                        ->default(false),

                                    Forms\Components\ToggleButtons::make('has_textile')
                                        ->label('Tekstil?')
                                        ->boolean()
                                        ->grouped()
                                        ->default(false),
                                ],
                                default => [],
                            })
                            ->key('dynamicVehicleFields'),
                    ]),

                Forms\Components\Section::make('Araç İlişkilendirmeleri')
                    ->columns([
                        'lg' => 2,
                        'xl' => 4,
                    ])
                    ->icon('heroicon-m-rectangle-stack')
                    ->schema(function (Get $get): array {
                        $relationshipComponents = [
                            Forms\Components\Select::make('carrier_id')
                                ->label('Tedarikçi')
                                ->relationship(name: 'carrier', titleAttribute: 'name')
                                ->createOptionForm([
                                    Forms\Components\TextInput::make('name')
                                        ->label('Tedarikçi Adı')
                                        ->maxLength(255)
                                        ->required(),

                                    Forms\Components\TextInput::make('tax_number')
                                        ->label('Vergi Numarası')
                                        ->maxLength(255),

                                    Forms\Components\TextInput::make('tax_office')
                                        ->label('Vergi Dairesi')
                                        ->maxLength(255),

                                    Forms\Components\TextInput::make('address')
                                        ->label('Adres')
                                        ->maxLength(255),

                                    Forms\Components\TextInput::make('telefon')
                                        ->label('Telefon')
                                        ->maxLength(255),

                                    Forms\Components\TextInput::make('email')
                                        ->label('E-posta Adresi')
                                        ->maxLength(150),

                                    Forms\Components\TextInput::make('website')
                                        ->label('Website')
                                        ->prefix('https://')
                                        ->maxLength(255),
                                ])
                                ->createOptionAction(function (Action $action) {
                                    return $action
                                        ->modalHeading('Tedarikçi Oluştur')
                                        ->modalWidth(MaxWidth::Large)
                                        ->slideOver();
                                })
                                ->searchable()
                                ->required(),
                        ];

                        $dynamicVehicleFields = match ((string) $get('vehicle_type_id')) {
                            '1' => [
                                // Binek Araç
                                Forms\Components\Select::make('employee_id')
                                    ->label('Personel')
                                    ->relationship(
                                        name: 'employee',
                                        modifyQueryUsing: fn (Builder $query) => $query->orderBy('firstname')->orderBy('lastname'),
                                    )
                                    ->getOptionLabelFromRecordUsing(fn ($record) => "{$record->firstname} {$record->lastname}")
                                    ->searchable(['firstname', 'lastname']),
                            ],
                            '2' => [
                                // Çekici
                                Forms\Components\Select::make('employee_id')
                                    ->label('Personel')
                                    ->relationship(
                                        name: 'employee',
                                        modifyQueryUsing: fn (Builder $query) => $query->orderBy('firstname')->orderBy('lastname'),
                                    )
                                    ->getOptionLabelFromRecordUsing(fn ($record) => "{$record->firstname} {$record->lastname}")
                                    ->searchable(['firstname', 'lastname']),

                                Forms\Components\Select::make('trailer_id')
                                    ->label('Dorse')
                                    ->relationship(
                                        name: 'trailer',
                                        titleAttribute: 'license_plate',
                                        modifyQueryUsing: fn (Builder $query) => $query->where('vehicle_type_id', 3)
                                    )
                                    ->searchable(),
                            ],
                            default => [],
                        };

                        return array_merge($relationshipComponents, $dynamicVehicleFields);
                    })
                    // ->visible(fn (Get $get): bool => in_array($get('vehicle_type_id'), [1,2]))
                    ->key('dynamicVehicleFields'),

                Forms\Components\Section::make('Belgeler & Sertifikalar')
                    ->visible(fn ($operation) => $operation === 'create')
                    ->columns([
                        'lg' => 1,
                    ])
                    ->icon('heroicon-s-document-text')
                    ->schema([
                        Forms\Components\Repeater::make('certificates')
                            ->label('')
                            ->relationship('certificates')
                            ->schema([
                                Forms\Components\Select::make('certificate_type_id')
                                    ->label('Belge Türü')
                                    ->options(VehicleCertificateType::class)
                                    ->required()
                                    ->searchable()
                                    ->native(false)
                                    ->live()
                                    ->afterStateUpdated(function (Forms\Components\Select $component) {
                                        $component
                                            ->getContainer()
                                            ->getComponent('dynamicCertificateFields')
                                            ->getChildComponentContainer()
                                            ->fill();
                                    }),

                                Forms\Components\DatePicker::make('started_at')
                                    ->label('Başlangıç Tarihi')
                                    ->required(),

                                Forms\Components\DatePicker::make('ended_at')
                                    ->label('Bitiş Tarihi')
                                    ->required(),

                                Forms\Components\Grid::make(3)
                                    ->schema(fn (Get $get): array => self::getCertificateFields($get('certificate_type_id')))
                                    ->key('dynamicCertificateFields'),

                                // SpatieMediaLibraryFileUpload::make('attachments')
                                //     ->label('Dosya Eki')
                                //     ->disk('medias')
                                //     ->conversion('preview')
                                //     ->acceptedFileTypes([
                                //         'image/jpeg',
                                //         'image/jpeg',
                                //         'image/png',
                                //         'application/pdf',
                                //         'application/vnd.ms-excel',
                                //         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                                //         'application/msword',
                                //         'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                //     ])
                                //     ->columnSpanFull(),
                            ])
                            ->itemLabel(function (array $state): ?string {
                                return !empty($state['certificate_type_id'])
                                    ? VehicleCertificateType::from($state['certificate_type_id'])->getLabel()
                                    : null;
                            })
                            ->addActionLabel('Yeni Belge & Sertifika Ekle')
                            // ->orderColumn('sort_order')
                            // ->reorderable(true)
                            // ->reorderableWithButtons()
                            ->collapsible()
                            // ->collapsed()
                            ->deleteAction(fn (Forms\Components\Actions\Action $action) => $action->requiresConfirmation())
                            ->defaultItems(0)
                            ->columns(3),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('id', 'desc')
            ->heading(static::$pluralModelLabel.' Listesi')
            ->columns([
                Tables\Columns\TextColumn::make('country.alpha_2')
                    ->label('Ülke')
                    ->formatStateUsing(fn ($state): View => view(
                        'vendor.filament.components.avatar-circle',
                        ['title' => $state],
                    ))
                    ->width('1%'),

                Tables\Columns\TextColumn::make('license_plate')
                    ->label('Plaka')
                    // ->formatStateUsing(fn ($record): View => view(
                    //     'vendor.filament.components.vehicle-info-column',
                    //     [
                    //         'license_plate' => $record->license_plate,
                    //         'make'          => $record->make,
                    //         'model'         => $record->make,
                    //         'employee'      => $record->employee?->fullname,
                    //     ],
                    // ))
                    ->description(function ($record) {
                        if ($record->vehicle_type_id == 3) {
                            return ($record->length ?: '0.00').' x '.($record->width ?: '0.00').' x '.($record->height ?: '0.00').'m';
                        }

                        return ($record->make ?: '...').' / '.($record->model ?: '...');
                    })
                    ->weight(FontWeight::Medium)
                    ->searchable(),

                Tables\Columns\IconColumn::make('traffic_insurance')
                    ->label('Sigorta')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Trafik sigortası bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('insurance')
                    ->label('Kasko')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Kasko bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('vehicle_inspection')
                    ->label('Muayene')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Araç muayene bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('green_card')
                    ->label('Yeşil Kart')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Yeşil kart bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('roder_certificate')
                    ->label('Roder')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Roder belgesi bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('frc_certificate')
                    ->label('FRC')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'FRC belgesi bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('aitm_certificate')
                    ->label('Uygunluk')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Araç uygunluk belgesi bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\IconColumn::make('tachograph_inspection')
                    ->label('Takograf')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Takograf muayenesi bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter()
                    ->width('1%'),

                Tables\Columns\TextColumn::make('vehicle_type_id')
                    ->label('Tür')
                    ->formatStateUsing(fn ($state): string => VehicleType::from($state)->getLabel())
                    ->color(fn ($state) => VehicleType::from($state)->getColor())
                    ->icon(fn ($state) => VehicleType::from($state)->getIcon())
                    ->badge(),

                Tables\Columns\TextColumn::make('employee.fullname')
                    ->label('Personel')
                    ->badge()
                    ->placeholder('Personel seçilmedi.'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Oluşturma')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Güncelleme')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            // ->recordClasses(fn ($record) => match ((string) $record->vehicle_type_id) {
            //     '1' => 'opacity-90',
            //     '2' => 'border-s-2 border-orange-600 dark:border-orange-300',
            //     '3' => 'border-l-4 !border-l-danger500 bg-danger-50 dark:bg-gray-800',
            //     default => null
            // })
            ->filters([
                Tables\Filters\SelectFilter::make('euro_norm_id')
                    ->label('Avrupa Emisyon Standardı')
                    ->options(EuroNorm::class)
                    ->searchable(),

                Tables\Filters\SelectFilter::make('has_adr_certificate')
                    ->label('ADR sertifikası var mı?')
                    ->options([
                        0 => 'Hayır',
                        1 => 'Evet',
                    ])
                    ->native(false),

            ], layout: FiltersLayout::Modal)
            ->filtersTriggerAction(
                fn (\Filament\Tables\Actions\Action $action) => $action->slideOver()
            )
            ->recordUrl(null)
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),

                    Tables\Actions\EditAction::make(),

                    Tables\Actions\DeleteAction::make()
                        ->label('Arşive Taşı')
                        ->icon('heroicon-o-archive-box')
                        ->color('warning')
                        ->modalIcon('heroicon-o-archive-box')
                        ->modalHeading(static::$modelLabel.' Arşivlenecek'),

                    Tables\Actions\ForceDeleteAction::make(),

                    Tables\Actions\RestoreAction::make(),
                ]),
            ])
            ->headerActions([
                ExportAction::make()->exports([
                    \App\Filament\Exports\VehicleExporter::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->label('Seçiliyi Arşive Taşı')
                        ->icon('heroicon-o-archive-box')
                        ->color('warning')
                        ->modalIcon('heroicon-o-archive-box')
                        ->modalHeading('Seçilen '.static::$pluralModelLabel.' Arşivlenecek'),

                    Tables\Actions\ForceDeleteBulkAction::make(),

                    Tables\Actions\RestoreBulkAction::make(),

                    ExportBulkAction::make()->exports([
                        \App\Filament\Exports\VehicleExporter::make(),
                    ]),
                ]),
            ])
            ->modifyQueryUsing(fn (Builder $query) => $query->with([
                'certificates',
            ]));
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Tabs::make('Tabs')
                    ->tabs([
                        Infolists\Components\Tabs\Tab::make('Araç Bilgileri')
                            ->schema([
                                Infolists\Components\TextEntry::make('country.alpha_2')
                                    ->label('Ülke:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('license_plate')
                                    ->label('Plaka:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('vehicle_type_id')
                                    ->label('Araç Türü:')
                                    ->formatStateUsing(fn ($state): string => VehicleType::from($state)->getLabel())
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('vin')
                                    ->label('Şasi Numarası:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('make')
                                    ->label('Marka:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('model')
                                    ->label('Model:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('year')
                                    ->label('Üretim Yılı:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('color')
                                    ->label('Renk:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('length')
                                    ->label('Uzunluk:')
                                    ->getStateUsing(fn ($record) => $record->length ? $record->length.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('width')
                                    ->label('Genişlik:')
                                    ->getStateUsing(fn ($record) => $record->width ? $record->width.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('height')
                                    ->label('Yükseklik:')
                                    ->getStateUsing(fn ($record) => $record->height ? $record->height.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('has_double_deck')
                                    ->label('Çift Kat:')
                                    ->formatStateUsing(function ($record) {
                                        if ($record->vehicle_type_id == 3) {
                                            return $record->has_double_deck ? 'Evet' : 'Hayır';
                                        }

                                        return '-';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('has_partition')
                                    ->label('Ek Bölme:')
                                    ->formatStateUsing(function ($record) {
                                        if ($record->vehicle_type_id == 3) {
                                            return $record->has_partition ? 'Evet' : 'Hayır';
                                        }

                                        return '-';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('has_textile')
                                    ->label('Tekstil:')
                                    ->formatStateUsing(function ($record) {
                                        if ($record->vehicle_type_id == 3) {
                                            return $record->has_textile ? 'Evet' : 'Hayır';
                                        }

                                        return '-';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('has_adr_certificate')
                                    ->label('ADR Belgesi:')
                                    ->formatStateUsing(function ($record) {
                                        return $record->has_adr_certificate ? 'Var' : 'Yok';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('euro_norm_id')
                                    ->label('Euro Norm:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('fuel_type_id')
                                    ->label('Yakıt Türü:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('employee.fullname')
                                    ->label('Personel Bilgisi:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.license_plate')
                                    ->label('Dorse:')
                                    ->inlineLabel()
                                    ->default('-'),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Belgeler & Sertifikalar')
                            ->schema([
                                Infolists\Components\TextEntry::make('traffic_insurance')
                                    ->label('Trafik Sigortası:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('insurance')
                                    ->label('Kasko:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('vehicle_inspection')
                                    ->label('Araç Muayenesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('green_card')
                                    ->label('Yeşil Kart:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('l_certificate')
                                    ->label('L Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 5)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('aitm_certificate')
                                    ->label('Araç Uygunluk Belgesi (AİTM):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('frc_certificate')
                                    ->label('FRC Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('roder_certificate')
                                    ->label('Roder Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('registration_card')
                                    ->label('Taşıt Kartı:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 9)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('tachograph_inspection')
                                    ->label('Takograf Muayenesi (TÜV):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('imm_certificate')
                                    ->label('İhtiyari Mali Mesuliyet Sigortası (İMM):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->certificates->where('certificate_type_id', 11)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Personel Bilgileri')
                            ->schema([
                                //
                                Infolists\Components\TextEntry::make('employee.fullname')
                                    ->label('Personel:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('employee.phones.phone_number')
                                    ->label('Telefon:')
                                    ->formatStateUsing(function ($record): string {
                                        if (!optional($record->employee->phones->where('is_primary', true)->first())->name) {
                                            return '';
                                        }

                                        return optional($record->employee->phones->where('is_primary', true)->first())->phone_number;
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('employee.passport_number')
                                    ->label('Pasaport Numarası:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('employee.passport_expiry_date')
                                    ->label('Pasaport:')
                                    ->formatStateUsing(function ($state): string {
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Pasaport bilgisi bulunamadı.')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('employee.adr_driver_training')
                                    ->label('SRC-5 Belgesi:')
                                    ->formatStateUsing(function ($state): string {
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'SRC-5 bilgisi bulunamadı.')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('travel_health_insurance')
                                    ->label('Sağlık Sigortası:')
                                    ->getStateUsing(function ($record): string {
                                        if (optional($record->employee)) {
                                            return '-';
                                        }

                                        $state = $record->employee->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Seyahat sağlık sigortası bilgisi bulunamadı.')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('tachograph_driver_card')
                                    ->label('Sürücü Kartı:')
                                    ->getStateUsing(function ($record): string {
                                        if (optional($record->employee)) {
                                            return '-';
                                        }

                                        $state = $record->employee->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Sürücü kartı sigortası bilgisi bulunamadı.')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Dorse Bilgileri')
                            ->visible(fn ($record): bool => $record->vehicle_type_id == 2)
                            ->schema([
                                Infolists\Components\TextEntry::make('trailer.country.alpha_2')
                                    ->label('Ülke:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.license_plate')
                                    ->label('Plaka:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.vin')
                                    ->label('Şasi Numarası:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.make')
                                    ->label('Marka:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.model')
                                    ->label('Model:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.year')
                                    ->label('Üretim Yılı:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.color')
                                    ->label('Renk:')
                                    ->inlineLabel()
                                    ->default('-'),

                                Infolists\Components\TextEntry::make('trailer.length')
                                    ->label('Uzunluk:')
                                    ->formatStateUsing(fn ($state) => $state ? $state.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.width')
                                    ->label('Genişlik:')
                                    ->formatStateUsing(fn ($state) => $state ? $state.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.height')
                                    ->label('Yükseklik:')
                                    ->formatStateUsing(fn ($state) => $state ? $state.'m' : '-')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.has_double_deck')
                                    ->label('Çift Kat:')
                                    ->formatStateUsing(function ($state) {
                                        return $state ? 'Evet' : 'Hayır';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.has_partition')
                                    ->label('Ek Bölme:')
                                    ->formatStateUsing(function ($state) {
                                        return $state ? 'Evet' : 'Hayır';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.has_textile')
                                    ->label('Tekstil:')
                                    ->formatStateUsing(function ($state) {
                                        return $state ? 'Evet' : 'Hayır';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('trailer.has_adr_certificate')
                                    ->label('ADR Belgesi:')
                                    ->formatStateUsing(function ($state) {
                                        return $state ? 'Var' : 'Yok';
                                    })
                                    ->inlineLabel(),

                                // DORSE BELGELER
                                Infolists\Components\TextEntry::make('trailer.traffic_insurance')
                                    ->label('Trafik Sigortası:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('insurance')
                                    ->label('Kasko:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('vehicle_inspection')
                                    ->label('Araç Muayenesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('green_card')
                                    ->label('Yeşil Kart:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('l_certificate')
                                    ->label('L Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 5)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('aitm_certificate')
                                    ->label('Araç Uygunluk Belgesi (AİTM):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('frc_certificate')
                                    ->label('FRC Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('roder_certificate')
                                    ->label('Roder Belgesi:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('registration_card')
                                    ->label('Taşıt Kartı:')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 9)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('tachograph_inspection')
                                    ->label('Takograf Muayenesi (TÜV):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('imm_certificate')
                                    ->label('İhtiyari Mali Mesuliyet Sigortası (İMM):')
                                    ->getStateUsing(function ($record) {
                                        $state = $record->trailer->certificates->where('certificate_type_id', 11)->sortByDesc('ended_at')->first()?->ended_at;
                                        $expiryDate = Carbon::parse($state);
                                        $today = Carbon::today();

                                        return $expiryDate->isPast()
                                            ? ($state ? 'Süresi doldu.' : '-')
                                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                                    })
                                    ->inlineLabel(),
                            ]),

                        // Infolists\Components\Tabs\Tab::make('asdasd')
                        //     ->schema([
                        //         //
                        //     ]),
                    ])
                    ->contained(true),
            ])
            ->columns(1);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getRecordSubNavigation(Page $page): array
    {
        return $page->generateNavigationItems([
            Pages\EditVehicle::class,
            Pages\ManageCertificates::class,
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListVehicles::route('/'),
            'create' => Pages\CreateVehicle::route('/create'),
            'edit' => Pages\EditVehicle::route('/{record}/edit'),
            'certificates' => Pages\ManageCertificates::route('/{record}/certificates'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }

    public static function getCertificateFields($typeId = null)
    {
       return match ((string) $typeId) {
            '1' => [
                // Trafik Sigortası
                Forms\Components\Select::make('insurance_company_id')
                    ->label('Sigorta Şirketi')
                    ->options(InsuranceCompany::all()->pluck('name', 'id'))
                    ->searchable(),

                Forms\Components\TextInput::make('policy_number')
                    ->label('Poliçe Numarası')
                    ->maxLength(50),

                Forms\Components\TextInput::make('insurance_agent')
                    ->label('Acente')
                    ->maxLength(255),
            ],
            '2' => [
                // Kasko Sigortası
                Forms\Components\Select::make('insurance_company_id')
                    ->label('Sigorta Şirketi')
                    ->options(InsuranceCompany::all()->pluck('name', 'id'))
                    ->searchable(),

                Forms\Components\TextInput::make('policy_number')
                    ->label('Poliçe Numarası')
                    ->maxLength(50),

                Forms\Components\TextInput::make('insurance_agent')
                    ->label('Acente')
                    ->maxLength(255),
            ],
            '3' => [
                // Araç Muayenesi
            ],
            '4' => [
                // Yeşil Kart
                Forms\Components\Select::make('insurance_company_id')
                    ->label('Sigorta Şirketi')
                    ->options(InsuranceCompany::all()->pluck('name', 'id'))
                    ->searchable()
                    ->required(),

                Forms\Components\TextInput::make('policy_number')
                    ->label('Poliçe Numarası')
                    ->maxLength(50),

                Forms\Components\TextInput::make('insurance_agent')
                    ->label('Acente')
                    ->maxLength(255),
            ],
            '5' => [
                // L Belgesi
                Forms\Components\Select::make('insurance_company_id')
                    ->label('Sigorta Şirketi')
                    ->options(InsuranceCompany::all()->pluck('name', 'id'))
                    ->searchable()
                    ->required(),

                Forms\Components\TextInput::make('policy_number')
                    ->label('Poliçe Numarası')
                    ->maxLength(50),

                Forms\Components\TextInput::make('insurance_agent')
                    ->label('Acente')
                    ->maxLength(255),
            ],
            '6' => [
                // Araç Uygunluk Belgesi
            ],
            '7' => [
                // FRC Belgesi
            ],
            '8' => [
                // Roder Belgesi
            ],
            '9' => [
                // Taşıt Kartı
            ],
            '10' => [
                // Takograf Muayenesi (TÜV)
            ],
            '11' => [
                // İMM
                Forms\Components\Select::make('insurance_company_id')
                    ->label('Sigorta Şirketi')
                    ->options(InsuranceCompany::all()->pluck('name', 'id'))
                    ->searchable()
                    ->required(),

                Forms\Components\TextInput::make('policy_number')
                    ->label('Poliçe Numarası')
                    ->maxLength(50),

                Forms\Components\TextInput::make('insurance_agent')
                    ->label('Acente')
                    ->maxLength(255),
            ],
            default => [
                //
            ],
       };
    }
}
