<?php

namespace App\Filament\Resources\AduanResource\Tables;

use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;

class AduansTable
{
    public static function configure(Table $table): Table
    {
        return $table
            // 🔥 SORT PRIORITAS + TANGGAL
            ->modifyQueryUsing(function ($query) {
                $query->orderByRaw("
                    CASE 
                        WHEN prioritas = 'penting' THEN 1
                        WHEN prioritas = 'biasa' THEN 2
                        ELSE 3
                    END
                ")->orderBy('created_at', 'desc');
            })

            // 🔥 FILTER
            ->filters([
                SelectFilter::make('status')
                    ->label('Filter Status')
                    ->options([
                        'menunggu' => 'Menunggu',
                        'diproses' => 'Diproses',
                        'selesai'  => 'Selesai',
                    ]),
                SelectFilter::make('desa')
                    ->label('Filter Desa')
                    ->options([
                        'botorejo'    => 'Botorejo',
                        'bunderan'    => 'Bunderan',
                        'doreng'      => 'Doreng',
                        'getas'       => 'Getas',
                        'jogoloyo'    => 'Jogoloyo',
                        'kalianyar'   => 'Kalianyar',
                        'karangrejo'  => 'Karangrejo',
                        'karangrowo'  => 'Karangrowo',
                        'kendaldoyong'=> 'Kendaldoyong',
                        'kerangkulon' => 'Kerangkulon',
                        'kuncir'      => 'Kuncir',
                        'lempuyang'   => 'Lempuyang',
                        'mojodemak'   => 'Mojodemak',
                        'mranak'      => 'Mranak',
                        'mrisen'      => 'Mrisen',
                        'pilangrejo'  => 'Pilangrejo',
                        'sidomulyo'   => 'Sido Mulyo',
                        'tlogodowo'   => 'Tlogodowo',
                        'tlogorejo'   => 'Tlogorejo',
                        'trengguli'   => 'Trengguli',
                        'wonosalam'   => 'Wonosalam',
                    ]),
                SelectFilter::make('prioritas')
                    ->label('Filter Prioritas')
                    ->options([
                        'penting' => 'Penting',
                        'biasa'   => 'Biasa',
                    ]),
            ])

            ->columns([

                // Foto Thumbnail — klik untuk lihat ukuran penuh
                ImageColumn::make('foto')
                    ->label('Foto')
                    ->disk('public')
                    ->height(60)
                    ->width(80)
                    ->url(fn ($record) => $record->foto ? asset('storage/' . $record->foto) : null)
                    ->openUrlInNewTab()
                    ->defaultImageUrl('https://ui-avatars.com/api/?name=NA&background=e2e8f0&color=94a3b8'),

                // Isi Aduan
                TextColumn::make('isi_aduan')
                    ->label('Isi Aduan')
                    ->limit(50)
                    ->searchable()
                    ->wrap(),

                // Nama Pelapor
                TextColumn::make('nama_pelapor')
                    ->label('Pelapor')
                    ->default('Anonim')
                    ->searchable(),

                // Desa
                BadgeColumn::make('desa')
                    ->label('Desa')
                    ->formatStateUsing(fn($state) => $state ? ucfirst($state) : '-')
                    ->color('info'),

                // Kategori ML
                BadgeColumn::make('kategori')
                    ->label('Kategori')
                    ->formatStateUsing(function ($state) {
                        if (!$state) return ['Belum Diproses'];

                        $items = explode(', ', $state);

                        return array_map(function ($item) {
                            return match ($item) {
                                'pelayanan_administrasi'  => 'Pelayanan Administrasi',
                                'infrastruktur_fasilitas' => 'Infrastruktur & Fasilitas',
                                'kebersihan_lingkungan'   => 'Kebersihan & Lingkungan',
                                'layanan_publik_utilitas' => 'Layanan Publik & Utilitas',
                                'keamanan_ketertiban'     => 'Keamanan & Ketertiban',
                                'sosial_kesejahteraan'    => 'Sosial & Kesejahteraan',
                                default                    => ucfirst(str_replace('_', ' ', $item)),
                            };
                        }, $items);
                    })
                    ->colors([
                        'primary' => fn($state) => str_contains($state ?? '', 'pelayanan'),
                        'danger'  => fn($state) => str_contains($state ?? '', 'infrastruktur'),
                        'success' => fn($state) => str_contains($state ?? '', 'kebersihan'),
                        'warning' => fn($state) => str_contains($state ?? '', 'layanan'),
                        'gray'    => fn($state) => str_contains($state ?? '', 'keamanan'),
                        'info'    => fn($state) => str_contains($state ?? '', 'sosial'),
                    ]),

                // Confidence Score
                TextColumn::make('confidence_score')
                    ->label('Skor ML (%)')
                    ->suffix('%')
                    ->default('-')
                    ->badge()
                    ->color(fn($state) => match(true) {
                        $state >= 80 => 'success',
                        $state >= 50 => 'warning',
                        default      => 'danger',
                    }),

                // Status
                BadgeColumn::make('status')
                    ->label('Status')
                    ->colors([
                        'primary' => 'menunggu',
                        'warning' => 'diproses',
                        'success' => 'selesai',
                    ]),

                // Prioritas
                BadgeColumn::make('prioritas')
                    ->label('Prioritas')
                    ->colors([
                        'danger'  => 'penting',
                        'success' => 'biasa',
                    ]),

                // Tanggal
                TextColumn::make('created_at')
                    ->label('Tanggal')
                    ->dateTime('d M Y')
                    ->sortable(),

            ])
            ->actions([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
            ])
            ->emptyStateHeading('Belum ada aduan aktif')
            ->emptyStateDescription('Data aduan masyarakat Kecamatan Wonosalam akan muncul di sini.');
    }
}
