<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BusinessTripResource\Pages;
use App\Models\BusinessTrip;
use App\Models\Office;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Table;

class BusinessTripResource extends Resource
{
    protected static ?string $model = BusinessTrip::class;

    protected static ?string $navigationIcon = 'heroicon-o-paper-airplane';

    protected static ?string $navigationGroup = 'Perjalanan Dinas';

    protected static ?string $navigationLabel = 'Perjalanan Dinas';

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'title';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Informasi Perjalanan')
                            ->description('Detail utama perjalanan dinas')
                            ->icon('heroicon-o-paper-airplane')
                            ->schema([
                                Forms\Components\Select::make('user_id')
                                    ->label('Karyawan')
                                    ->relationship('user', 'name', fn ($query) => $query->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-user'),
                                Forms\Components\Select::make('company_id')
                                    ->label('Perusahaan')
                                    ->relationship('company', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-building-office'),
                                Forms\Components\TextInput::make('title')
                                    ->label('Judul/Keperluan')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-document-text')
                                    ->columnSpanFull()
                                    ->placeholder('Contoh: Koordinasi dengan BPKP Jawa Timur'),
                                Forms\Components\Textarea::make('description')
                                    ->label('Deskripsi Kegiatan')
                                    ->rows(3)
                                    ->columnSpanFull()
                                    ->placeholder('Jelaskan detail kegiatan perjalanan dinas...'),
                                Forms\Components\TextInput::make('surat_tugas_number')
                                    ->label('No. Surat Tugas')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-document-duplicate')
                                    ->placeholder('ST/xxx/2024'),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Tujuan Perjalanan')
                            ->description('Lokasi dan instansi tujuan')
                            ->icon('heroicon-o-map-pin')
                            ->schema([
                                Forms\Components\Grid::make(2)
                                    ->schema([
                                        Forms\Components\TextInput::make('destination_city')
                                            ->label('Kota Tujuan')
                                            ->required()
                                            ->maxLength(255)
                                            ->prefixIcon('heroicon-o-building-office-2')
                                            ->placeholder('Jakarta'),
                                        Forms\Components\TextInput::make('destination_province')
                                            ->label('Provinsi Tujuan')
                                            ->required()
                                            ->maxLength(255)
                                            ->prefixIcon('heroicon-o-globe-asia-australia')
                                            ->placeholder('DKI Jakarta'),
                                    ]),
                                Forms\Components\Select::make('destination_office_id')
                                    ->label('Instansi Tujuan (dari daftar)')
                                    ->relationship('destinationOffice', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-building-library')
                                    ->helperText('Pilih dari daftar BPKP/Pemda yang tersedia'),
                                Forms\Components\TextInput::make('destination_institution')
                                    ->label('Nama Instansi (manual)')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-building-office')
                                    ->helperText('Isi jika instansi tidak ada di daftar')
                                    ->placeholder('Nama instansi tujuan'),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Periode & Transportasi')
                            ->description('Jadwal dan moda transportasi')
                            ->icon('heroicon-o-calendar-days')
                            ->schema([
                                Forms\Components\DatePicker::make('start_date')
                                    ->label('Tanggal Berangkat')
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-arrow-right-circle')
                                    ->displayFormat('d M Y'),
                                Forms\Components\DatePicker::make('end_date')
                                    ->label('Tanggal Kembali')
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-arrow-left-circle')
                                    ->afterOrEqual('start_date')
                                    ->displayFormat('d M Y'),
                                Forms\Components\ToggleButtons::make('transportation_type')
                                    ->label('Jenis Transportasi')
                                    ->options([
                                        'pesawat' => 'Pesawat',
                                        'kereta' => 'Kereta',
                                        'bus' => 'Bus',
                                        'mobil_dinas' => 'Mobil Dinas',
                                        'mobil_pribadi' => 'Mobil Pribadi',
                                        'lainnya' => 'Lainnya',
                                    ])
                                    ->icons([
                                        'pesawat' => 'heroicon-o-paper-airplane',
                                        'kereta' => 'heroicon-o-truck',
                                        'bus' => 'heroicon-o-truck',
                                        'mobil_dinas' => 'heroicon-o-truck',
                                        'mobil_pribadi' => 'heroicon-o-truck',
                                        'lainnya' => 'heroicon-o-ellipsis-horizontal',
                                    ])
                                    ->colors([
                                        'pesawat' => 'info',
                                        'kereta' => 'warning',
                                        'bus' => 'success',
                                        'mobil_dinas' => 'primary',
                                        'mobil_pribadi' => 'primary',
                                        'lainnya' => 'gray',
                                    ])
                                    ->inline()
                                    ->columnSpanFull(),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Lokasi Rumah (Referensi)')
                            ->description('Koordinat untuk validasi kehadiran')
                            ->icon('heroicon-o-home')
                            ->schema([
                                Forms\Components\TextInput::make('home_latitude')
                                    ->label('Latitude')
                                    ->numeric()
                                    ->step(0.00000001)
                                    ->prefixIcon('heroicon-o-map-pin'),
                                Forms\Components\TextInput::make('home_longitude')
                                    ->label('Longitude')
                                    ->numeric()
                                    ->step(0.00000001)
                                    ->prefixIcon('heroicon-o-map-pin'),
                            ])
                            ->columns(2)
                            ->collapsible()
                            ->collapsed(),
                    ])
                    ->columnSpan(['lg' => 2]),

                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Status Perjalanan')
                            ->icon('heroicon-o-flag')
                            ->schema([
                                Forms\Components\ToggleButtons::make('status')
                                    ->label('')
                                    ->options([
                                        'pending' => 'Menunggu',
                                        'approved' => 'Disetujui',
                                        'rejected' => 'Ditolak',
                                        'ongoing' => 'Berlangsung',
                                        'completed' => 'Selesai',
                                    ])
                                    ->icons([
                                        'pending' => 'heroicon-o-clock',
                                        'approved' => 'heroicon-o-check-circle',
                                        'rejected' => 'heroicon-o-x-circle',
                                        'ongoing' => 'heroicon-o-play',
                                        'completed' => 'heroicon-o-check-badge',
                                    ])
                                    ->colors([
                                        'pending' => 'warning',
                                        'approved' => 'info',
                                        'rejected' => 'danger',
                                        'ongoing' => 'primary',
                                        'completed' => 'success',
                                    ])
                                    ->default('pending')
                                    ->required()
                                    ->inline()
                                    ->columnSpanFull()
                                    ->disabled(fn() => !auth()->user()->hasPermissionTo('approve_business_trips')),
                            ])
                            ->visible(fn(string $operation): bool => $operation === 'edit'),

                        Forms\Components\Section::make('Ringkasan')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                Forms\Components\Placeholder::make('duration_preview')
                                    ->label('Durasi Perjalanan')
                                    ->content(function ($get) {
                                        $start = $get('start_date');
                                        $end = $get('end_date');
                                        if ($start && $end) {
                                            $days = \Carbon\Carbon::parse($start)->diffInDays(\Carbon\Carbon::parse($end)) + 1;
                                            return $days . ' hari';
                                        }
                                        return '-';
                                    }),
                                Forms\Components\Placeholder::make('route_preview')
                                    ->label('Rute')
                                    ->content(function ($get) {
                                        $city = $get('destination_city');
                                        $province = $get('destination_province');
                                        if ($city && $province) {
                                            return $city . ', ' . $province;
                                        }
                                        return '-';
                                    }),
                            ])
                            ->visible(fn(string $operation): bool => $operation !== 'create'),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\Layout\Split::make([
                    Tables\Columns\Layout\Stack::make([
                        Tables\Columns\ImageColumn::make('user.avatar')
                            ->circular()
                            ->size(45)
                            ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->user?->name ?? 'N/A') . '&background=3b82f6&color=fff&bold=true'),
                    ])->grow(false),

                    Tables\Columns\Layout\Stack::make([
                        Tables\Columns\TextColumn::make('user.name')
                            ->label('Karyawan')
                            ->weight(FontWeight::Bold)
                            ->searchable()
                            ->sortable(),
                        Tables\Columns\TextColumn::make('title')
                            ->label('Keperluan')
                            ->color('gray')
                            ->size('sm')
                            ->limit(40)
                            ->searchable(),
                    ]),

                    Tables\Columns\Layout\Stack::make([
                        Tables\Columns\TextColumn::make('destination_city')
                            ->label('Tujuan')
                            ->icon('heroicon-m-map-pin')
                            ->iconColor('primary')
                            ->size('sm')
                            ->searchable(),
                        Tables\Columns\Layout\Split::make([
                            Tables\Columns\TextColumn::make('start_date')
                                ->label('Berangkat')
                                ->date('d M')
                                ->size('sm')
                                ->color('gray'),
                            Tables\Columns\TextColumn::make('end_date')
                                ->label('Kembali')
                                ->date('d M')
                                ->size('sm')
                                ->color('gray')
                                ->prefix('- '),
                        ]),
                    ])->visibleFrom('md'),

                    Tables\Columns\Layout\Stack::make([
                        Tables\Columns\TextColumn::make('transportation_type')
                            ->label('Transportasi')
                            ->badge()
                            ->formatStateUsing(fn(?string $state): string => match ($state) {
                                'pesawat' => 'Pesawat',
                                'kereta' => 'Kereta',
                                'bus' => 'Bus',
                                'mobil_dinas' => 'Mobil Dinas',
                                'mobil_pribadi' => 'Mobil Pribadi',
                                'lainnya' => 'Lainnya',
                                default => '-',
                            })
                            ->color(fn(?string $state): string => match ($state) {
                                'pesawat' => 'info',
                                'kereta' => 'warning',
                                'bus' => 'success',
                                'mobil_dinas', 'mobil_pribadi' => 'primary',
                                default => 'gray',
                            }),
                        Tables\Columns\TextColumn::make('status')
                            ->label('Status')
                            ->badge()
                            ->color(fn(string $state): string => match ($state) {
                                'pending' => 'warning',
                                'approved' => 'info',
                                'rejected' => 'danger',
                                'ongoing' => 'primary',
                                'completed' => 'success',
                                default => 'gray',
                            })
                            ->formatStateUsing(fn(string $state): string => match ($state) {
                                'pending' => 'Menunggu',
                                'approved' => 'Disetujui',
                                'rejected' => 'Ditolak',
                                'ongoing' => 'Berlangsung',
                                'completed' => 'Selesai',
                                default => $state,
                            }),
                    ])->alignEnd(),
                ])->from('md'),

                Tables\Columns\Layout\Panel::make([
                    Tables\Columns\Layout\Split::make([
                        Tables\Columns\TextColumn::make('surat_tugas_number')
                            ->label('No. Surat Tugas')
                            ->icon('heroicon-m-document-duplicate')
                            ->iconColor('primary')
                            ->placeholder('-'),
                        Tables\Columns\TextColumn::make('destinationOffice.name')
                            ->label('Instansi')
                            ->icon('heroicon-m-building-library')
                            ->iconColor('warning')
                            ->placeholder(fn($record) => $record->destination_institution ?: '-')
                            ->limit(30),
                        Tables\Columns\TextColumn::make('duration')
                            ->label('Durasi')
                            ->state(fn($record) => $record->getDurationDays() . ' hari')
                            ->icon('heroicon-m-calendar-days')
                            ->iconColor('success'),
                    ]),
                ])->collapsible(),
            ])
            ->contentGrid([
                'md' => 1,
                'xl' => 1,
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'pending' => 'Menunggu Approval',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                        'ongoing' => 'Sedang Berlangsung',
                        'completed' => 'Selesai',
                    ])
                    ->native(false)
                    ->indicator('Status'),
                Tables\Filters\SelectFilter::make('transportation_type')
                    ->label('Transportasi')
                    ->options([
                        'pesawat' => 'Pesawat',
                        'kereta' => 'Kereta Api',
                        'bus' => 'Bus',
                        'mobil_dinas' => 'Mobil Dinas',
                        'mobil_pribadi' => 'Mobil Pribadi',
                        'lainnya' => 'Lainnya',
                    ])
                    ->native(false)
                    ->indicator('Transportasi'),
                Tables\Filters\SelectFilter::make('user_id')
                    ->label('Karyawan')
                    ->relationship('user', 'name')
                    ->searchable()
                    ->preload()
                    ->native(false)
                    ->indicator('Karyawan'),
                Tables\Filters\Filter::make('date_range')
                    ->form([
                        Forms\Components\DatePicker::make('start_from')
                            ->label('Dari Tanggal')
                            ->native(false)
                            ->prefixIcon('heroicon-o-calendar'),
                        Forms\Components\DatePicker::make('start_until')
                            ->label('Sampai Tanggal')
                            ->native(false)
                            ->prefixIcon('heroicon-o-calendar'),
                    ])
                    ->query(function ($query, array $data) {
                        return $query
                            ->when($data['start_from'], fn($q) => $q->whereDate('start_date', '>=', $data['start_from']))
                            ->when($data['start_until'], fn($q) => $q->whereDate('start_date', '<=', $data['start_until']));
                    })
                    ->columns(2)
                    ->indicateUsing(function (array $data): ?string {
                        if (!$data['start_from'] && !$data['start_until']) {
                            return null;
                        }
                        return 'Periode: ' . ($data['start_from'] ?? '...') . ' - ' . ($data['start_until'] ?? '...');
                    }),
            ])
            ->filtersFormColumns(2)
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->icon('heroicon-o-eye'),
                    Tables\Actions\EditAction::make()
                        ->icon('heroicon-o-pencil-square'),
                    Tables\Actions\Action::make('approve')
                        ->label('Approve')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-check-circle')
                        ->modalIconColor('success')
                        ->modalHeading('Approve Perjalanan Dinas')
                        ->modalDescription('Apakah Anda yakin ingin menyetujui perjalanan dinas ini?')
                        ->visible(fn(BusinessTrip $record): bool => $record->status === 'pending' && auth()->user()->hasPermissionTo('approve_business_trips'))
                        ->action(function (BusinessTrip $record) {
                            $record->update([
                                'status' => 'approved',
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                            ]);
                            Notification::make()
                                ->success()
                                ->title('Perjalanan Dinas Disetujui')
                                ->body('Perjalanan dinas ke ' . $record->destination_city . ' telah disetujui.')
                                ->icon('heroicon-o-check-circle')
                                ->iconColor('success')
                                ->send();
                        }),
                    Tables\Actions\Action::make('reject')
                        ->label('Reject')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->modalIcon('heroicon-o-x-circle')
                        ->modalIconColor('danger')
                        ->form([
                            Forms\Components\Textarea::make('rejection_reason')
                                ->label('Alasan Penolakan')
                                ->placeholder('Jelaskan alasan penolakan...')
                                ->required()
                                ->rows(3),
                        ])
                        ->visible(fn(BusinessTrip $record): bool => $record->status === 'pending' && auth()->user()->hasPermissionTo('approve_business_trips'))
                        ->action(function (BusinessTrip $record, array $data) {
                            $record->update([
                                'status' => 'rejected',
                                'rejection_reason' => $data['rejection_reason'],
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                            ]);
                            Notification::make()
                                ->success()
                                ->title('Perjalanan Dinas Ditolak')
                                ->body('Perjalanan dinas ke ' . $record->destination_city . ' telah ditolak.')
                                ->icon('heroicon-o-x-circle')
                                ->iconColor('danger')
                                ->send();
                        }),
                    Tables\Actions\Action::make('startTrip')
                        ->label('Mulai Perjalanan')
                        ->icon('heroicon-o-play')
                        ->color('primary')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-play')
                        ->modalIconColor('primary')
                        ->modalHeading('Mulai Perjalanan Dinas')
                        ->modalDescription('Tandai perjalanan dinas ini sebagai sedang berlangsung?')
                        ->visible(fn(BusinessTrip $record): bool => $record->status === 'approved')
                        ->action(function (BusinessTrip $record) {
                            $record->update(['status' => 'ongoing']);
                            Notification::make()
                                ->success()
                                ->title('Perjalanan Dinas Dimulai')
                                ->body('Perjalanan dinas ke ' . $record->destination_city . ' sekarang sedang berlangsung.')
                                ->icon('heroicon-o-play')
                                ->send();
                        }),
                    Tables\Actions\Action::make('completeTrip')
                        ->label('Selesaikan')
                        ->icon('heroicon-o-check-badge')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-check-badge')
                        ->modalIconColor('success')
                        ->modalHeading('Selesaikan Perjalanan Dinas')
                        ->modalDescription('Tandai perjalanan dinas ini sebagai selesai?')
                        ->visible(fn(BusinessTrip $record): bool => $record->status === 'ongoing')
                        ->action(function (BusinessTrip $record) {
                            $record->update(['status' => 'completed']);
                            Notification::make()
                                ->success()
                                ->title('Perjalanan Dinas Selesai')
                                ->body('Perjalanan dinas ke ' . $record->destination_city . ' telah diselesaikan.')
                                ->icon('heroicon-o-check-badge')
                                ->send();
                        }),
                    Tables\Actions\DeleteAction::make()
                        ->icon('heroicon-o-trash'),
                ])
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->tooltip('Aksi'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->icon('heroicon-o-trash'),
                    Tables\Actions\BulkAction::make('approveSelected')
                        ->label('Approve Terpilih')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-check-circle')
                        ->modalIconColor('success')
                        ->visible(fn() => auth()->user()->hasPermissionTo('approve_business_trips'))
                        ->action(function ($records) {
                            $count = 0;
                            $records->each(function ($record) use (&$count) {
                                if ($record->status === 'pending') {
                                    $record->update([
                                        'status' => 'approved',
                                        'approved_by' => auth()->id(),
                                        'approved_at' => now(),
                                    ]);
                                    $count++;
                                }
                            });
                            Notification::make()
                                ->success()
                                ->title('Perjalanan Dinas Disetujui')
                                ->body($count . ' perjalanan dinas berhasil disetujui.')
                                ->icon('heroicon-o-check-circle')
                                ->send();
                        }),
                ]),
            ])
            ->defaultSort('created_at', 'desc')
            ->striped()
            ->poll('30s');
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make()
                    ->schema([
                        Infolists\Components\Split::make([
                            Infolists\Components\ImageEntry::make('user.avatar')
                                ->label('')
                                ->circular()
                                ->size(80)
                                ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->user?->name ?? 'N/A') . '&background=3b82f6&color=fff&bold=true&size=80')
                                ->grow(false),
                            Infolists\Components\Group::make([
                                Infolists\Components\TextEntry::make('user.name')
                                    ->label('')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold),
                                Infolists\Components\TextEntry::make('title')
                                    ->label('')
                                    ->icon('heroicon-o-document-text')
                                    ->iconColor('primary'),
                            ]),
                        ])->from('md'),
                    ]),

                Infolists\Components\Grid::make(3)
                    ->schema([
                        Infolists\Components\Section::make('Tujuan')
                            ->icon('heroicon-o-map-pin')
                            ->iconColor('primary')
                            ->schema([
                                Infolists\Components\TextEntry::make('destination_city')
                                    ->label('Kota')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold),
                                Infolists\Components\TextEntry::make('destination_province')
                                    ->label('Provinsi'),
                                Infolists\Components\TextEntry::make('destinationOffice.name')
                                    ->label('Instansi')
                                    ->placeholder(fn($record) => $record->destination_institution ?: '-'),
                            ]),

                        Infolists\Components\Section::make('Periode')
                            ->icon('heroicon-o-calendar-days')
                            ->iconColor('success')
                            ->schema([
                                Infolists\Components\TextEntry::make('start_date')
                                    ->label('Berangkat')
                                    ->date('l, d F Y')
                                    ->icon('heroicon-o-arrow-right-circle')
                                    ->iconColor('success'),
                                Infolists\Components\TextEntry::make('end_date')
                                    ->label('Kembali')
                                    ->date('l, d F Y')
                                    ->icon('heroicon-o-arrow-left-circle')
                                    ->iconColor('danger'),
                                Infolists\Components\TextEntry::make('duration')
                                    ->label('Durasi')
                                    ->state(fn($record) => $record->getDurationDays() . ' hari')
                                    ->weight(FontWeight::Bold),
                            ]),

                        Infolists\Components\Section::make('Status')
                            ->icon('heroicon-o-flag')
                            ->iconColor('warning')
                            ->schema([
                                Infolists\Components\TextEntry::make('status')
                                    ->label('Status Perjalanan')
                                    ->badge()
                                    ->size('lg')
                                    ->color(fn(string $state): string => match ($state) {
                                        'pending' => 'warning',
                                        'approved' => 'info',
                                        'rejected' => 'danger',
                                        'ongoing' => 'primary',
                                        'completed' => 'success',
                                        default => 'gray',
                                    }),
                                Infolists\Components\TextEntry::make('transportation_type')
                                    ->label('Transportasi')
                                    ->badge()
                                    ->color(fn(?string $state): string => match ($state) {
                                        'pesawat' => 'info',
                                        'kereta' => 'warning',
                                        'bus' => 'success',
                                        'mobil_dinas', 'mobil_pribadi' => 'primary',
                                        default => 'gray',
                                    }),
                                Infolists\Components\TextEntry::make('surat_tugas_number')
                                    ->label('No. Surat Tugas')
                                    ->icon('heroicon-o-document-duplicate')
                                    ->placeholder('-'),
                            ]),
                    ]),

                Infolists\Components\Section::make('Deskripsi')
                    ->icon('heroicon-o-document-text')
                    ->schema([
                        Infolists\Components\TextEntry::make('description')
                            ->label('')
                            ->placeholder('Tidak ada deskripsi'),
                    ])
                    ->collapsible(),

                Infolists\Components\Section::make('Informasi Approval')
                    ->icon('heroicon-o-shield-check')
                    ->schema([
                        Infolists\Components\TextEntry::make('approver.name')
                            ->label('Diproses Oleh')
                            ->icon('heroicon-o-user')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('approved_at')
                            ->label('Tanggal Proses')
                            ->dateTime('d M Y H:i')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->placeholder('-')
                            ->visible(fn($record) => $record->status === 'rejected'),
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('Dibuat')
                            ->dateTime('d M Y H:i'),
                    ])
                    ->columns(4)
                    ->collapsible(),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBusinessTrips::route('/'),
            'create' => Pages\CreateBusinessTrip::route('/create'),
            'view' => Pages\ViewBusinessTrip::route('/{record}'),
            'edit' => Pages\EditBusinessTrip::route('/{record}/edit'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('status', 'pending')->count() ?: null;
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'warning';
    }

    public static function getGloballySearchableAttributes(): array
    {
        return ['title', 'user.name', 'destination_city', 'destination_province', 'surat_tugas_number'];
    }

    public static function getGlobalSearchResultDetails($record): array
    {
        return [
            'Karyawan' => $record->user?->name ?? '-',
            'Tujuan' => $record->destination_city . ', ' . $record->destination_province,
            'Status' => match ($record->status) {
                'pending' => 'Menunggu',
                'approved' => 'Disetujui',
                'rejected' => 'Ditolak',
                'ongoing' => 'Berlangsung',
                'completed' => 'Selesai',
                default => $record->status,
            },
        ];
    }

    /**
     * Hide super_admin business trips from all lists
     */
    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::getEloquentQuery();

        // Hide super_admin business trips (using Spatie roles)
        $query->whereHas('user', function ($q) {
            $q->whereDoesntHave('roles', function ($r) {
                $r->where('name', 'super_admin');
            });
        });

        // Admin biasa hanya lihat company mereka
        $user = auth()->user();
        if ($user && !$user->hasRole('super_admin')) {
            $query->where('company_id', $user->company_id);
        }

        return $query;
    }
}
