<?php

namespace App\Filament\Resources\Coupons\Tables;

use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class CouponsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('code')
                    ->label('Code')
                    ->searchable()
                    ->copyable()
                    ->copyMessage('Coupon code copied')
                    ->copyMessageDuration(1500),

                TextColumn::make('name')
                    ->label('Name')
                    ->searchable()
                    ->limit(30),

                TextColumn::make('type')
                    ->badge()
                    ->label('Type')
                    ->colors([
                        'blue' => 'percentage',
                        'green' => 'fixed',
                    ]),

                TextColumn::make('formatted_discount')
                    ->label('Discount')
                    ->sortable(),

                TextColumn::make('uses_count')
                    ->label('Used')
                    ->sortable()
                    ->alignCenter(),

                TextColumn::make('remaining_uses')
                    ->label('Remaining')
                    ->getStateUsing(fn ($record) => $record->remaining_uses ?? '∞')
                    ->sortable()
                    ->alignCenter(),

                IconColumn::make('is_active')
                    ->label('Active')
                    ->boolean()
                    ->alignCenter(),

                TextColumn::make('expires_at')
                    ->label('Expires')
                    ->dateTime('M j, Y')
                    ->sortable()
                    ->color(fn ($record): string => $record->isExpiringSoon() ? 'warning' : 'default')
                    ->description(fn ($record): string => $record->expires_at ? $record->expires_at->diffForHumans() : ''
                    ),

                TextColumn::make('created_at')
                    ->label('Created')
                    ->dateTime('M j, Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('type')
                    ->options([
                        'percentage' => 'Percentage',
                        'fixed' => 'Fixed Amount',
                    ]),

                SelectFilter::make('is_active')
                    ->options([
                        '1' => 'Active',
                        '0' => 'Inactive',
                    ]),

                SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'valid' => 'Valid',
                        'expired' => 'Expired',
                        'used_up' => 'Used Up',
                    ])
                    ->query(fn ($query, $data) => match ($data['value']) {
                        'valid' => $query->valid(),
                        'expired' => $query->where('expires_at', '<', now()),
                        'used_up' => $query->whereRaw('uses_count >= max_uses'),
                        default => $query,
                    }),
            ])
            ->recordActions([
                EditAction::make(),

                Action::make('duplicate')
                    ->label('Duplicate')
                    ->icon('heroicon-o-document-duplicate')
                    ->color('gray')
                    ->action(function ($record) {
                        $newCoupon = $record->replicate();
                        $newCoupon->code = $newCoupon->code.'_COPY';
                        $newCoupon->uses_count = 0;
                        $newCoupon->save();
                    })
                    ->successNotificationTitle('Coupon duplicated successfully'),

                Action::make('view_usage')
                    ->label('View Usage')
                    ->icon('heroicon-o-chart-bar')
                    ->color('blue')
                    ->url(fn ($record) => route('filament.admin.resources.coupons.usage', $record)),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),

                BulkAction::make('bulk_deactivate')
                    ->label('Deactivate')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->action(function (\Illuminate\Support\Collection $records) {
                        $records->each->update(['is_active' => false]);
                    })
                    ->deselectRecordsAfterCompletion(),

                BulkAction::make('bulk_activate')
                    ->label('Activate')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->action(function (\Illuminate\Support\Collection $records) {
                        $records->each->update(['is_active' => true]);
                    })
                    ->deselectRecordsAfterCompletion(),
            ])
            ->emptyStateActions([
                CreateAction::make(),
            ])
            ->poll('60s');
    }
}
