<?php

namespace App\Filament\Resources\Audits\Tables;

use App\Models\Audit;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class AuditsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('auditor.name')->label('Auditor'),
                TextColumn::make('model_type')->label('Tipe Objek')
                    ->formatStateUsing(fn ($state) => match ($state) {
                        'App\\Models\\CashRecord' => '💰 Transaksi Kas',
                        'App\\Models\\Activity'   => '📅 Kegiatan',
                        'App\\Models\\User'       => '👤 Anggota',
                        default                   => class_basename($state),
                    }),
                TextColumn::make('subject')->label('Objek')
                    ->state(function (Audit $record): string {
                        $subject = $record->auditable;
                        return match (true) {
                            $subject instanceof \App\Models\CashRecord =>
                                $subject->description . ' — Rp ' . number_format($subject->amount, 0, ',', '.'),
                            $subject instanceof \App\Models\Activity => $subject->title,
                            $subject instanceof \App\Models\User     => $subject->name,
                            default => "#{$record->model_id}",
                        };
                    })->limit(45),
                TextColumn::make('issue_type')->label('Jenis')->badge()
                    ->formatStateUsing(fn ($state) => $state === 'critical' ? '🚨 Kritis' : '⚠️ Peringatan')
                    ->color(fn ($state) => $state === 'critical' ? 'danger' : 'warning'),
                TextColumn::make('description')->label('Temuan')->limit(50),
                TextColumn::make('status')->badge()
                    ->formatStateUsing(fn ($state) => $state === 'resolved' ? 'Selesai' : 'Terbuka')
                    ->color(fn ($state) => $state === 'resolved' ? 'success' : 'danger'),
                TextColumn::make('created_at')->label('Tanggal')->date('d M Y')->sortable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                SelectFilter::make('issue_type')->label('Jenis')
                    ->options(['warning' => 'Peringatan', 'critical' => 'Kritis']),
                SelectFilter::make('status')
                    ->options(['open' => 'Terbuka', 'resolved' => 'Selesai']),
            ])
            ->recordActions([EditAction::make()])
            ->toolbarActions([BulkActionGroup::make([DeleteBulkAction::make()])]);
    }
}
