<?php

namespace App\Filament\Widgets;

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

class BusinessTripStatusWidget extends BaseWidget
{
    protected static ?int $sort = 5;

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

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

    protected static ?string $pollingInterval = '30s';

    public function table(Table $table): Table
    {
        return $table
            ->query(
                BusinessTrip::query()
                    ->where('status', 'pending')
                    ->with(['user'])
                    // Hide super_admin
                    ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                    ->latest()
                    ->limit(5)
            )
            ->columns([
                Tables\Columns\Layout\Stack::make([
                    Tables\Columns\Layout\Split::make([
                        Tables\Columns\Layout\Stack::make([
                            Tables\Columns\TextColumn::make('user.name')
                                ->label('Karyawan')
                                ->weight('bold')
                                ->size('sm'),

                            Tables\Columns\TextColumn::make('title')
                                ->label('Keperluan')
                                ->size('xs')
                                ->color('gray')
                                ->limit(30),
                        ]),
                    ]),

                    Tables\Columns\Layout\Split::make([
                        Tables\Columns\TextColumn::make('destination_city')
                            ->label('Tujuan')
                            ->size('xs')
                            ->badge()
                            ->color('info')
                            ->icon('heroicon-m-map-pin'),

                        Tables\Columns\TextColumn::make('transportation_type')
                            ->label('Transport')
                            ->size('xs')
                            ->badge()
                            ->color('gray')
                            ->formatStateUsing(fn(?string $state): string => match ($state) {
                                'pesawat' => 'Pesawat',
                                'kereta' => 'Kereta',
                                'bus' => 'Bus',
                                'mobil_dinas' => 'Dinas',
                                'mobil_pribadi' => 'Pribadi',
                                default => $state ?? '-',
                            }),
                    ]),

                    Tables\Columns\Layout\Split::make([
                        Tables\Columns\TextColumn::make('start_date')
                            ->label('Berangkat')
                            ->date('d M')
                            ->size('xs')
                            ->icon('heroicon-m-calendar'),

                        Tables\Columns\TextColumn::make('end_date')
                            ->label('Kembali')
                            ->date('d M Y')
                            ->size('xs')
                            ->color('gray'),

                        Tables\Columns\TextColumn::make('duration')
                            ->label('Durasi')
                            ->state(fn($record) => $record->getDurationDays() . ' hari')
                            ->size('xs')
                            ->badge()
                            ->color('warning'),
                    ]),
                ])->space(2),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\Action::make('approve')
                        ->label('Setujui')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalHeading('Setujui Perjalanan Dinas')
                        ->modalDescription(fn(BusinessTrip $record) => "Setujui perjalanan dinas {$record->user->name} ke {$record->destination_city}?")
                        ->modalSubmitActionLabel('Ya, Setujui')
                        ->visible(fn() => auth()->user()->hasPermissionTo('approve_business_trips'))
                        ->action(function (BusinessTrip $record) {
                            $record->update([
                                'status' => 'approved',
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                            ]);

                            Notification::make()
                                ->title('Perjalanan Dinas Disetujui')
                                ->success()
                                ->send();
                        }),

                    Tables\Actions\Action::make('reject')
                        ->label('Tolak')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->requiresConfirmation()
                        ->form([
                            \Filament\Forms\Components\Textarea::make('rejection_reason')
                                ->label('Alasan Penolakan')
                                ->required(),
                        ])
                        ->visible(fn() => 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()
                                ->title('Perjalanan Dinas Ditolak')
                                ->warning()
                                ->send();
                        }),

                    Tables\Actions\Action::make('view')
                        ->label('Detail')
                        ->icon('heroicon-o-eye')
                        ->color('gray')
                        ->url(fn(BusinessTrip $record) => route('filament.admin.resources.business-trips.edit', $record)),
                ])->iconButton(),
            ])
            ->paginated(false)
            ->emptyStateHeading('Tidak Ada Pending')
            ->emptyStateDescription('Semua perjalanan dinas sudah diproses.')
            ->emptyStateIcon('heroicon-o-paper-airplane');
    }
}
