<?php

namespace App\Filament\Widgets;

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

class PendingApprovalsWidget extends BaseWidget
{
    protected static ?int $sort = 3;

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

    protected static ?string $heading = 'Menunggu Persetujuan';

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

    public function table(Table $table): Table
    {
        return $table
            ->query(
                User::query()
                    ->where('approval_status', 'pending')
                    // Hide super_admin
                    ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
                    ->latest()
            )
            ->columns([
                Tables\Columns\ImageColumn::make('avatar')
                    ->label('')
                    ->circular()
                    ->size(40)
                    ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->name) . '&background=1565C0&color=fff&size=100'),

                Tables\Columns\TextColumn::make('name')
                    ->label('Nama')
                    ->weight('bold')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('email')
                    ->label('Email')
                    ->color('gray')
                    ->searchable(),

                Tables\Columns\TextColumn::make('department')
                    ->label('Departemen')
                    ->badge()
                    ->color('gray')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('position')
                    ->label('Jabatan')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('company.name')
                    ->label('Perusahaan')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Mendaftar')
                    ->since()
                    ->sortable(),
            ])
            ->actions([
                Tables\Actions\Action::make('approve')
                    ->label('Setujui')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->modalHeading('Setujui Pendaftaran')
                    ->modalDescription(fn(User $record) => "Apakah Anda yakin ingin menyetujui pendaftaran {$record->name}?")
                    ->modalSubmitActionLabel('Ya, Setujui')
                    ->action(function (User $record) {
                        $record->update([
                            'approval_status' => 'approved',
                            'approved_by' => auth()->id(),
                            'approved_at' => now(),
                            'is_active' => true,
                        ]);

                        Notification::make()
                            ->title('Pendaftaran Disetujui')
                            ->body($record->name . ' berhasil disetujui.')
                            ->success()
                            ->send();
                    }),

                Tables\Actions\Action::make('reject')
                    ->label('Tolak')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading('Tolak Pendaftaran')
                    ->form([
                        \Filament\Forms\Components\Textarea::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->required()
                            ->placeholder('Masukkan alasan penolakan...'),
                    ])
                    ->action(function (User $record, array $data) {
                        $record->update([
                            'approval_status' => 'rejected',
                            'rejection_reason' => $data['rejection_reason'],
                            'approved_by' => auth()->id(),
                            'approved_at' => now(),
                            'is_active' => false,
                        ]);

                        Notification::make()
                            ->title('Pendaftaran Ditolak')
                            ->body($record->name . ' telah ditolak.')
                            ->warning()
                            ->send();
                    }),

                Tables\Actions\Action::make('view')
                    ->label('Detail')
                    ->icon('heroicon-o-eye')
                    ->color('gray')
                    ->url(fn(User $record) => route('filament.admin.resources.users.edit', $record)),
            ])
            ->defaultPaginationPageOption(5)
            ->emptyStateHeading('Semua Terverifikasi')
            ->emptyStateDescription('Tidak ada pendaftaran yang menunggu persetujuan.')
            ->emptyStateIcon('heroicon-o-check-badge')
            ->striped();
    }
}
