<?php

namespace App\Filament\Resources\Votes\Tables;

use App\Models\Vote;
use App\Models\VoteItem;
use Filament\Actions\Action;
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 VotesTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('title')->label('Judul')->searchable(),
                TextColumn::make('type')->badge(),
                TextColumn::make('status')->badge()
                    ->color(fn ($state) => $state === 'open' ? 'success' : 'gray'),
                TextColumn::make('deadline')->label('Batas Waktu')->dateTime('d M Y H:i'),
                TextColumn::make('items_count')->counts('items')->label('Suara'),
                TextColumn::make('result')
                    ->label('Hasil')
                    ->state(function (Vote $record): string {
                        $total    = $record->items()->count();
                        $approve  = $record->items()->where('choice', 'approve')->count();
                        $reject   = $record->items()->where('choice', 'reject')->count();
                        $abstain  = $record->items()->where('choice', 'abstain')->count();

                        if ($total === 0) return '-';

                        return "✓{$approve} ✗{$reject} ○{$abstain}";
                    }),
            ])
            ->filters([
                SelectFilter::make('status')->options(['open' => 'Buka', 'closed' => 'Tutup']),
                SelectFilter::make('type')->options([
                    'activity' => 'Kegiatan',
                    'finance'  => 'Keuangan',
                    'general'  => 'Umum',
                ]),
            ])
            ->recordActions([
                Action::make('vote')
                    ->label('Beri Suara')
                    ->icon('heroicon-o-hand-raised')
                    ->color('info')
                    ->visible(fn (Vote $record) => $record->status === 'open'
                        && ! $record->items()->where('user_id', auth()->id())->exists()
                        && (! $record->deadline || $record->deadline->isFuture()))
                    ->form([
                        \Filament\Forms\Components\Radio::make('choice')
                            ->label('Pilihan Anda')
                            ->options([
                                'approve' => '✓ Setuju',
                                'reject'  => '✗ Tidak Setuju',
                                'abstain' => '○ Abstain',
                            ])
                            ->required(),
                    ])
                    ->action(function (Vote $record, array $data): void {
                        VoteItem::create([
                            'vote_id' => $record->id,
                            'user_id' => auth()->id(),
                            'choice'  => $data['choice'],
                        ]);

                        \App\Models\ActivityLog::create([
                            'user_id'     => auth()->id(),
                            'action'      => 'voted',
                            'model_type'  => Vote::class,
                            'model_id'    => $record->id,
                            'description' => auth()->user()->name . " memilih {$data['choice']} pada voting '{$record->title}'",
                        ]);
                    }),

                Action::make('close')
                    ->label('Tutup Voting')
                    ->icon('heroicon-o-lock-closed')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->visible(fn (Vote $record) => $record->status === 'open')
                    ->action(function (Vote $record): void {
                        $record->update(['status' => 'closed']);

                        \App\Models\ActivityLog::create([
                            'user_id'     => auth()->id(),
                            'action'      => 'vote_closed',
                            'model_type'  => Vote::class,
                            'model_id'    => $record->id,
                            'description' => "Voting '{$record->title}' ditutup",
                        ]);
                    }),

                EditAction::make(),
                ViewAction::make()->label('Detail'),
            ])
            ->toolbarActions([BulkActionGroup::make([DeleteBulkAction::make()])]);
    }
}
