<?php

namespace App\Filament\Resources\Posts\Tables;

use App\Services\NotificationService;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class PostsTable
{
    public static function configure(Table $table): Table
    {
        $isAdmin = auth()->user()?->hasAnyRole(['super_admin', 'ketua']);

        return $table
            ->columns([
                TextColumn::make('title')->label('Judul')->searchable()->sortable(),
                TextColumn::make('category')->label('Kategori')->badge()
                    ->color(fn ($state) => match ($state) {
                        'pengumuman' => 'warning',
                        'berita'     => 'info',
                        default      => 'gray',
                    }),
                TextColumn::make('status')->badge()
                    ->color(fn ($state) => match ($state) {
                        'published' => 'success',
                        'pending'   => 'warning',
                        'rejected'  => 'danger',
                        default     => 'gray',
                    }),
                TextColumn::make('author.name')->label('Penulis')->visible($isAdmin),
                TextColumn::make('rejection_reason')->label('Alasan Penolakan')
                    ->limit(40)->default('-')
                    ->visible(fn ($record) => $record?->status === 'rejected'),
                TextColumn::make('published_at')->label('Dipublikasi')
                    ->dateTime('d M Y')->default('-')->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')->options([
                    'draft'     => 'Draft',
                    'pending'   => 'Menunggu',
                    'published' => 'Diterbitkan',
                    'rejected'  => 'Ditolak',
                ]),
            ])
            ->recordActions([
                // Untuk anggota/pengurus/bendahara: ajukan artikel
                Action::make('submit')
                    ->label('Ajukan')
                    ->icon('heroicon-o-paper-airplane')
                    ->color('info')
                    ->requiresConfirmation()
                    ->visible(fn ($record) => ! $isAdmin && in_array($record->status, ['draft', 'rejected']))
                    ->action(function ($record): void {
                        $record->update(['status' => 'pending', 'rejection_reason' => null]);
                        NotificationService::toRole('ketua', 'Artikel Menunggu Persetujuan',
                            "\"{$record->title}\" oleh {$record->author->name} menunggu persetujuan.", 'warning',
                            route('filament.admin.resources.posts.edit', $record));
                    }),

                // Untuk admin: approve
                Action::make('publish')
                    ->label('Terbitkan')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->visible(fn ($record) => $isAdmin && $record->status === 'pending')
                    ->action(fn ($record) => tap($record->update([
                        'status'       => 'published',
                        'published_at' => now(),
                        'reviewed_by'  => auth()->id(),
                    ]), fn () => NotificationService::send(
                        $record->author, 'Artikel Diterbitkan',
                        "Artikel \"{$record->title}\" Anda telah diterbitkan.", 'success',
                        route('filament.admin.resources.posts.edit', $record)
                    ))),

                // Untuk admin: tolak
                Action::make('reject')
                    ->label('Tolak')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(fn ($record) => $isAdmin && $record->status === 'pending')
                    ->form([
                        Textarea::make('rejection_reason')->label('Alasan Penolakan')->required(),
                    ])
                    ->action(fn ($record, array $data) => tap($record->update([
                        'status'           => 'rejected',
                        'reviewed_by'      => auth()->id(),
                        'rejection_reason' => $data['rejection_reason'],
                    ]), fn () => NotificationService::send(
                        $record->author, 'Artikel Ditolak',
                        "Artikel \"{$record->title}\" ditolak: {$data['rejection_reason']}", 'danger',
                        route('filament.admin.resources.posts.edit', $record)
                    ))),

                EditAction::make()
                    ->visible(fn ($record) => $isAdmin || in_array($record->status, ['draft', 'rejected'])),
            ])
            ->toolbarActions([BulkActionGroup::make([DeleteBulkAction::make()])]);
    }
}
