<?php

namespace App\Filament\Widgets;

use App\Models\BusinessTrip;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class RecentBusinessTripsWidget extends BaseWidget
{
    protected static ?int $sort = 2;

    protected int|string|array $columnSpan = [
        'md' => 2,
        'xl' => 1,
    ];

    protected static ?string $heading = 'Perjalanan Dinas Terbaru';

    public function table(Table $table): Table
    {
        return $table
            ->query(
                BusinessTrip::query()
                    ->with(['user', 'destinationOffice'])
                    // Hide super_admin
                    ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                    ->latest()
                    ->limit(5)
            )
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Karyawan')
                    ->searchable(),
                Tables\Columns\TextColumn::make('title')
                    ->label('Keperluan')
                    ->limit(30),
                Tables\Columns\TextColumn::make('destination_city')
                    ->label('Tujuan'),
                Tables\Columns\TextColumn::make('start_date')
                    ->label('Berangkat')
                    ->date('d M Y'),
                Tables\Columns\TextColumn::make('end_date')
                    ->label('Kembali')
                    ->date('d M Y'),
                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,
                    }),
            ])
            ->actions([
                Tables\Actions\Action::make('view')
                    ->label('Lihat')
                    ->icon('heroicon-o-eye')
                    ->url(fn(BusinessTrip $record) => route('filament.admin.resources.business-trips.edit', $record)),
            ])
            ->emptyStateHeading('Belum ada perjalanan dinas')
            ->emptyStateDescription('Data perjalanan dinas akan muncul di sini.')
            ->emptyStateIcon('heroicon-o-paper-airplane');
    }
}
