<?php

namespace App\Filament\Widgets;

use App\Models\Attendance;
use App\Models\User;
use Carbon\Carbon;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;

class AbsentEmployeesWidget extends BaseWidget
{
    protected static ?string $heading = 'Karyawan Belum Absen Hari Ini';

    protected static ?int $sort = 2;

    protected int|string|array $columnSpan = 'full';

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

    public function table(Table $table): Table
    {
        return $table
            ->query(
                User::query()
                    ->where('is_active', true)
                    ->where('approval_status', 'approved')
                    // Hide super_admin
                    ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
                    ->whereDoesntHave('attendances', function (Builder $query) {
                        $query->whereDate('date', Carbon::today());
                    })
                    ->orderBy('name')
            )
            ->columns([
                Tables\Columns\ImageColumn::make('avatar')
                    ->label('')
                    ->circular()
                    ->size(40)
                    ->defaultImageUrl(fn ($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->name) . '&background=ef4444&color=fff&bold=true'),
                Tables\Columns\TextColumn::make('name')
                    ->label('Nama Karyawan')
                    ->searchable()
                    ->sortable()
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('nip')
                    ->label('NIP')
                    ->searchable()
                    ->placeholder('-'),
                Tables\Columns\TextColumn::make('department')
                    ->label('Departemen')
                    ->searchable()
                    ->placeholder('-'),
                Tables\Columns\TextColumn::make('position')
                    ->label('Jabatan')
                    ->searchable()
                    ->placeholder('-'),
                Tables\Columns\TextColumn::make('company.name')
                    ->label('Perusahaan')
                    ->searchable()
                    ->placeholder('-'),
                Tables\Columns\IconColumn::make('absent_status')
                    ->label('Status')
                    ->state(fn () => 'absent')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->tooltip('Belum Absen'),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('company_id')
                    ->label('Perusahaan')
                    ->relationship('company', 'name')
                    ->searchable()
                    ->preload(),
                Tables\Filters\SelectFilter::make('department')
                    ->label('Departemen')
                    ->options(fn () => User::whereNotNull('department')->distinct()->pluck('department', 'department')->toArray())
                    ->searchable(),
            ])
            ->actions([
                Tables\Actions\Action::make('send_reminder')
                    ->label('Kirim Pengingat')
                    ->icon('heroicon-o-bell-alert')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->modalHeading('Kirim Pengingat Absen')
                    ->modalDescription(fn (User $record) => "Kirim pengingat absen ke {$record->name}?")
                    ->action(function (User $record) {
                        // TODO: Implementasi kirim notifikasi
                        \Filament\Notifications\Notification::make()
                            ->title('Pengingat Terkirim')
                            ->body("Pengingat absen telah dikirim ke {$record->name}")
                            ->success()
                            ->send();
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkAction::make('send_bulk_reminder')
                    ->label('Kirim Pengingat Massal')
                    ->icon('heroicon-o-bell-alert')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->modalHeading('Kirim Pengingat Massal')
                    ->modalDescription('Kirim pengingat absen ke semua karyawan yang dipilih?')
                    ->action(function ($records) {
                        // TODO: Implementasi kirim notifikasi massal
                        \Filament\Notifications\Notification::make()
                            ->title('Pengingat Terkirim')
                            ->body("Pengingat absen telah dikirim ke {$records->count()} karyawan")
                            ->success()
                            ->send();
                    }),
            ])
            ->emptyStateHeading('Semua Karyawan Sudah Absen')
            ->emptyStateDescription('Tidak ada karyawan yang belum melakukan absensi hari ini.')
            ->emptyStateIcon('heroicon-o-check-circle')
            ->striped()
            ->paginated([5, 10, 25]);
    }

    public static function canView(): bool
    {
        return auth()->user()?->hasAnyRole(['super_admin', 'admin', 'manager']) ?? false;
    }
}
