<?php

namespace App\Filament\Resources\OrderResource\Pages;

use App\Filament\Resources\OrderResource;
use App\Filament\Resources\OrderResource\Widgets\StatsOverview;
use App\Models\Order;
use Archilex\AdvancedTables\AdvancedTables;
use Filament\Actions;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Components\Tab;
use Filament\Resources\Pages\ListRecords;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;

class ListOrders extends ListRecords
{
    use AdvancedTables;

    protected static string $resource = OrderResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\CreateAction::make(),
        ];
    }

    protected function getHeaderWidgets(): array
    {
        return [
            // StatsOverview::class,
        ];
    }

    public function table(Table $table): Table
    {
        return parent::table($table)
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),

                    // Bulk approve action only visible on recommended tab
                    Tables\Actions\BulkAction::make('bulk_approve')
                        ->label(__('order.bulk_approve'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalHeading(__('order.bulk_approve_confirmation'))
                        ->modalDescription(__('order.bulk_approve_description'))
                        ->form([
                            Forms\Components\Radio::make('recommendation')
                                ->label(__(''))
                                ->options([
                                    'approve' => __('order.approve'),
                                    'reject' => __('order.reject'),
                                ])
                                ->inline()
                                ->live()
                                ->required(),

                            Forms\Components\Textarea::make('notes')
                                ->label(__('order.recommendation'))
                                ->visible(fn ($get) => $get('recommendation') === 'reject')
                                ->required(fn ($get) => $get('recommendation') === 'reject')
                                ->rows(3),
                        ])
                        ->action(function (Collection $records, array $data) {
                            $successCount = 0;
                            $failureCount = 0;
                            $pendingRequirementsCount = 0;

                            foreach ($records as $record) {
                                // Prepare notes
                                $recommendation = $data['recommendation'] ?? null;
                                $notes = __('order.'.$recommendation).': '.($data['notes'] ?? '');

                                // Check if there are pending requirements
                                if ($record->isTherePendingRequirements()) {
                                    $failureCount++;
                                    $pendingRequirementsCount++;

                                    continue;
                                }

                                // Approve to next stage
                                if ($record->approveToNextStage($notes)) {
                                    $successCount++;
                                } else {
                                    $failureCount++;
                                }
                            }

                            // Show notification based on results
                            if ($successCount > 0 && $failureCount === 0) {
                                Notification::make()
                                    ->title(__('order.bulk_approve_success', ['count' => $successCount]))
                                    ->success()
                                    ->send();
                            } elseif ($successCount > 0 && $failureCount > 0) {
                                $message = __('order.bulk_approve_partial_success', [
                                    'success' => $successCount,
                                    'failure' => $failureCount,
                                ]);

                                if ($pendingRequirementsCount > 0) {
                                    $message .= ' '.__('order.bulk_approve_pending_requirements', [
                                        'count' => $pendingRequirementsCount,
                                    ]);
                                }

                                Notification::make()
                                    ->title($message)
                                    ->warning()
                                    ->send();
                            } else {
                                $message = __('order.bulk_approve_failed');

                                if ($pendingRequirementsCount > 0) {
                                    $message = __('order.bulk_approve_failed_pending_requirements', [
                                        'count' => $pendingRequirementsCount,
                                    ]);
                                }

                                Notification::make()
                                    ->title($message)
                                    ->danger()
                                    ->send();
                            }
                        })
                        ->deselectRecordsAfterCompletion()
                        ->visible(fn () => $this->activeTab === 'recommended' && Auth::user()->can('provide_order_recommendation_order')),
                ]),
            ]);
    }

    public function getTabs(): array
    {
        $user = Auth::user();
        $tabs = [];

        if (Auth::user()->can('view_all_orders_order')) {
            // All orders tab
            $tabs['all'] = Tab::make(__('order.all'))
                ->badge(Order::filterByTypePermissions()->count());
        }

        // Status-specific tabs with permissions
        $statusTabs = [
            'created' => [
                'status' => Order::STATUS_CREATED,
                'permission' => 'view_created_orders_order',
                'label' => __('order.created'),
            ],
            'pending_recommendation' => [
                'status' => Order::STATUS_PENDING_RECOMMENDATION,
                'permission' => 'view_pending_recommendation_orders_order',
                'label' => __('order.pending_recommendation'),
            ],
            'recommended' => [
                'status' => Order::STATUS_RECOMMENDED,
                'permission' => 'view_recommended_orders_order',
                'label' => __('order.recommended'),
            ],
            'technical_financial_requested' => [
                'status' => Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED,
                'permission' => 'view_technical_financial_requested_orders_order',
                'label' => __('order.technical_financial_requested'),
            ],
            'technical_financial_approved' => [
                'status' => Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
                'permission' => 'view_technical_financial_approved_orders_order',
                'label' => __('order.technical_financial_approved'),
            ],
            'project_manager_approved' => [
                'status' => Order::STATUS_PROJECT_MANAGER_APPROVED,
                'permission' => 'view_project_manager_approved_orders_order',
                'label' => __('order.project_manager_approved'),
            ],
            'classification' => [
                'status' => Order::STATUS_CLASSIFICATION,
                'permission' => 'view_classification_orders_order',
                'label' => __('order.classification'),
            ],
            'agreement' => [
                'status' => Order::STATUS_AGREEMENT,
                'permission' => 'view_agreement_orders_order',
                'label' => __('order.agreement'),
            ],
            'ceo_approved' => [
                'status' => Order::STATUS_CEO_APPROVED,
                'permission' => 'view_ceo_approved_orders_order',
                'label' => __('order.ceo_approved'),
            ],
            'launched' => [
                'status' => Order::STATUS_LAUNCHED,
                'permission' => 'view_launched_orders_order',
                'label' => __('order.launched'),
            ],
            'accepted' => [
                'status' => Order::STATUS_ACCEPTED,
                'permission' => 'view_accepted_orders_order',
                'label' => __('order.accepted'),
            ],
            'rejected' => [
                'status' => Order::STATUS_REJECTED,
                'permission' => 'view_rejected_orders_order',
                'label' => __('order.rejected'),
            ],
        ];

        foreach ($statusTabs as $key => $config) {
            if ($user && $user->can($config['permission'])) {
                $tabs[$key] = Tab::make($config['label'])
                    ->modifyQueryUsing(fn (Builder $query) => $query->where('status', $config['status']))
                    ->badge(Order::filterByTypePermissions()->where('status', $config['status'])->count());
            }
        }

        return $tabs;
    }
}
