<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\MyProjects;
use App\Filament\Resources\ProjectCharterResource\Pages;
use App\Filament\Resources\ProjectCharterResource\RelationManagers;
use App\Models\InitiativeProject;
use App\Models\Order;
use App\Models\PerformanceCard;
use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Pages\SubNavigationPosition;
use Filament\Resources\Pages\Page;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\HtmlString;

class ProjectCharterResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ProjectCharter::class;

    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static ?int $navigationSort = 1;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    protected static ?string $cluster = MyProjects::class;

    public static function getNavigationLabel(): string
    {
        return __('project_charter.project_charters');
    }

    public static function getModelLabel(): string
    {
        return __('project_charter.project_charter');
    }

    public static function getPluralModelLabel(): string
    {
        return __('project_charter.project_charters');
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->ownScope();
    }

    public static function getAvailableOrderOptions(): array
    {
        Log::info('STATIC METHOD - Loading order options for project charter form...');

        try {
            $orders = Order::withoutGlobalScopes()
                ->where('status', Order::STATUS_ACCEPTED)
                ->whereDoesntHave('projectCharter')
                ->get();

            Log::info('STATIC METHOD - Found '.$orders->count().' available orders');

            if ($orders->isEmpty()) {
                Log::warning('STATIC METHOD - No orders found - returning empty array');

                return [];
            }

            // ->getOptionLabelFromRecordUsing(fn(\App\Models\Order $record): string => "#{$record->id} - " . (\App\Models\Order::getOrderTypes()[$record->type] ?? $record->type) . " - {$record->association->name}")
            $options = $orders->mapWithKeys(function ($order) {
                $displayText = "#{$order->id} - ".(\App\Models\Order::getOrderTypes()[$order->type] ?? $order->type)." - {$order->association->name}";

                return [$order->id => $displayText];
            })->toArray();

            Log::info('STATIC METHOD - Order options array count: '.count($options));
            Log::info('STATIC METHOD - First few options:', array_slice($options, 0, 3, true));

            return $options;
        } catch (\Exception $e) {
            Log::error('STATIC METHOD - Error loading order options: '.$e->getMessage());

            return [];
        }
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('project_charter.basic_information'))
                    ->schema([

                        // Store project manner for persistent visibility checks
                        Forms\Components\Hidden::make('project_manner')
                            ->default(fn (): ?string => request()->get('project_manner')),

                        // Order Selection (only for create operation)
                        Forms\Components\Select::make('order_id')
                            ->label(__('project_charter.linked_order'))
                            ->options(static::getAvailableOrderOptions())
                            ->searchable(['order_description', 'id'])
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
                                if ($state) {
                                    $order = \App\Models\Order::with(['agreement', 'finance'])->find($state);
                                    if ($order) {
                                        // Auto-fill fields from order
                                        $set('name', "#{$order->id} - ".(\App\Models\Order::getOrderTypes()[$order->type] ?? $order->type)." - {$order->association->name}");
                                        $set('description', $order->order_description ?? '');

                                        // Handle dates properly
                                        if ($order->agreement && $order->agreement->start_date) {
                                            $set('start_date', $order->agreement->start_date->format('Y-m-d'));
                                        }

                                        if ($order->agreement && $order->agreement->end_date) {
                                            $set('expected_end_date', $order->agreement->end_date->format('Y-m-d'));
                                        }

                                        // Handle financial data
                                        if ($order->finance) {
                                            $set('estimated_cost', $order->finance->approved_price);
                                            $set('total_cost', $order->finance->approved_price);
                                        }
                                    }
                                } else {
                                    // Clear auto-filled fields when order is deselected
                                    $set('name', '');
                                    $set('description', '');
                                    $set('start_date', null);
                                    $set('expected_end_date', null);
                                    $set('estimated_cost', null);
                                    $set('total_cost', null);
                                }
                            })
                            ->helperText(__('project_charter.order_selection_helper'))
                            ->visible(fn (string $operation, Forms\Get $get): bool => $operation === 'create' && $get('project_manner') === PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL),

                        // if the project manner is not developmental, then show a selection of one service provider
                        Forms\Components\Select::make('service_provider_id')
                            ->label(__('service_provider.service_provider'))
                            ->relationship('serviceProvider', 'name')
                            ->required()
                            ->searchable()
                            ->preload()
                            ->visible(fn (string $operation, Forms\Get $get): bool => $operation === 'create' && $get('project_manner') !== PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL),

                        // Preselect initiative project if provided in the request
                        Forms\Components\Hidden::make('initiative_project_id')
                            ->default(fn (?ProjectCharter $record): ?int => $record?->initiative_project_id ?? request()->get('initiative_project_id')),

                        // Show initiative project selection if not preselected
                        Forms\Components\Select::make('initiative_project_id')
                            ->label(__('project_charter.project_charter'))
                            ->relationship('initiativeProject', 'name')
                            ->required()
                            ->searchable()
                            ->preload()
                            ->visible(false),

                        Forms\Components\TextInput::make('name')
                            ->label(__('project_charter.name'))
                            ->required()
                            ->maxLength(255)
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated(), // Ensure value is included even when disabled

                        Forms\Components\Textarea::make('description')
                            ->label(__('project_charter.description'))
                            ->required()
                            ->rows(4)
                            ->maxLength(1000)
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated(), // Ensure value is included even when disabled

                        Forms\Components\Hidden::make('status')
                            ->default(ProjectCharter::STATUS_DRAFT),
                    ])
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter.dates_and_costs'))
                    ->schema([
                        Forms\Components\DatePicker::make('start_date')
                            ->label(__('project_charter.start_date'))
                            ->required()
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated() // Ensure value is included even when disabled
                            ->reactive()
                            ->afterOrEqual(function (Forms\Get $get) {
                                $initiativeProjectId = $get('initiative_project_id');
                                if ($initiativeProjectId) {
                                    $initiativeProject = InitiativeProject::with('initiative')->find($initiativeProjectId);

                                    return $initiativeProject?->initiative?->start_date;
                                }

                                return null;
                            })
                            ->beforeOrEqual(function (Forms\Get $get) {
                                $initiativeProjectId = $get('initiative_project_id');
                                if ($initiativeProjectId) {
                                    $initiativeProject = InitiativeProject::with('initiative')->find($initiativeProjectId);

                                    return $initiativeProject?->initiative?->expected_end_date;
                                }

                                return null;
                            }),

                        Forms\Components\DatePicker::make('expected_end_date')
                            ->label(__('project_charter.expected_end_date'))
                            ->required()
                            ->after('start_date')
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated() // Ensure value is included even when disabled
                            ->reactive()
                            ->afterOrEqual(function (Forms\Get $get) {
                                $initiativeProjectId = $get('initiative_project_id');
                                if ($initiativeProjectId) {
                                    $initiativeProject = InitiativeProject::with('initiative')->find($initiativeProjectId);

                                    return $initiativeProject?->initiative?->start_date;
                                }

                                return null;
                            })
                            ->beforeOrEqual(function (Forms\Get $get) {
                                $initiativeProjectId = $get('initiative_project_id');
                                if ($initiativeProjectId) {
                                    $initiativeProject = InitiativeProject::with('initiative')->find($initiativeProjectId);

                                    return $initiativeProject?->initiative?->expected_end_date;
                                }

                                return null;
                            }),

                        Forms\Components\TextInput::make('estimated_cost')
                            ->label(__('project_charter.estimated_cost'))
                            ->required()
                            ->numeric()
                            ->minValue(0)
                            ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                            ->reactive()
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated() // Ensure value is included even when disabled
                            ->helperText(function (Forms\Get $get, ?ProjectCharter $record) {
                                $initiativeProjectId = $get('initiative_project_id');
                                if (! $initiativeProjectId) {
                                    return __('project_charter.estimated_cost_helper');
                                }

                                $initiativeProject = InitiativeProject::with('initiative')->find($initiativeProjectId);
                                $initiative = $initiativeProject?->initiative;

                                if (! $initiative || ! $initiative->expected_cost) {
                                    return __('project_charter.estimated_cost_helper');
                                }

                                $currentTotal = $initiative->total_project_charters_estimated_cost;
                                // If editing, exclude current record from total
                                if ($record && $record->exists) {
                                    $currentTotal -= ($record->estimated_cost ?? 0);
                                }

                                $available = $initiative->expected_cost - $currentTotal;

                                return __('project_charter.estimated_cost_helper').' '.
                                    __('project_charter.initiative_budget_info', [
                                        'initiative_name' => $initiative->name,
                                        'initiative_budget' => number_format($initiative->expected_cost, 2),
                                        'current_total' => number_format($currentTotal, 2),
                                        'available' => number_format(max(0, $available), 2),
                                    ]);
                            }),

                        Forms\Components\TextInput::make('total_cost')
                            ->label(__('project_charter.total_cost'))
                            ->required()
                            ->numeric()
                            ->default(0)
                            ->minValue(0)
                            ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                            ->helperText(__('project_charter.total_cost_helper'))
                            ->disabled(fn (Forms\Get $get): bool => ! empty($get('order_id')))
                            ->dehydrated(), // Ensure value is included even when disabled
                    ])
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter.performance_tracking'))
                    ->schema([
                        Forms\Components\Select::make('performanceCardResults')
                            ->label(__('project_charter.performance_card_results'))
                            ->multiple()
                            ->searchable()
                            ->preload()
                            ->relationship(
                                'performanceCardResults',
                                'result',
                                function ($query, Forms\Get $get) {
                                    // Filter performance card results by the initiative
                                    if ($initiativeProjectId = $get('initiative_project_id')) {
                                        $query->whereHas('initiativeResults', function ($subQuery) use ($initiativeProjectId) {
                                            $subQuery->whereHas('initiative.projects', function ($projectQuery) use ($initiativeProjectId) {
                                                $projectQuery->where('initiative_projects.id', $initiativeProjectId);
                                            });
                                        });
                                    }
                                }
                            )
                            ->getOptionLabelFromRecordUsing(function ($record) {
                                return $record->performanceCard->name.' - '.$record->result;
                            })
                            ->getSearchResultsUsing(function (string $search, Forms\Get $get) {
                                $query = \App\Models\PerformanceCardResult::query()
                                    ->with('performanceCard')
                                    ->where(function ($q) use ($search) {
                                        $q->where('performance_card_results.result', 'ilike', "%{$search}%");
                                    });

                                // Filter by initiative project
                                if ($initiativeProjectId = $get('initiative_project_id')) {
                                    $query->whereHas('initiativeResults', function ($subQuery) use ($initiativeProjectId) {
                                        $subQuery->whereHas('initiative.projects', function ($projectQuery) use ($initiativeProjectId) {
                                            $projectQuery->where('initiative_projects.id', $initiativeProjectId);
                                        });
                                    });
                                }

                                return $query->limit(50)
                                    ->get()
                                    ->mapWithKeys(function ($result) {
                                        return [$result->id => $result->performanceCard->name.' - '.$result->result];
                                    });
                            })
                            ->helperText(__('project_charter.performance_card_results_helper'))
                            ->live(),
                    ])
                    ->columns(1),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('project_charter.name'))
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('start_date')
                    ->label(__('project_charter.start_date'))
                    ->date()
                    ->sortable(),

                Tables\Columns\TextColumn::make('expected_end_date')
                    ->label(__('project_charter.expected_end_date'))
                    ->date()
                    ->sortable(),

                Tables\Columns\TextColumn::make('estimated_cost')
                    ->label(__('project_charter.estimated_cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable(),

                Tables\Columns\TextColumn::make('total_cost')
                    ->label(__('project_charter.total_cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable(),

                Tables\Columns\TextColumn::make('description')
                    ->label(__('project_charter.description'))
                    ->sortable()
                    ->searchable(),

                // Tables\Columns\TextColumn::make('initiativeProject.name')
                //     ->label(__('project_charter.project_charter'))
                //     ->sortable()
                //     ->searchable(),

                // Tables\Columns\TextColumn::make('order.name')
                //     ->label(__('project_charter.linked_order'))
                //     ->sortable()
                //     ->searchable()
                //     ->formatStateUsing(fn($record) => $record->order ? "#{$record->order->id} - {$record->order->name}" : '-')
                //     ->placeholder('-'),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter.status'))
                    ->badge()
                    ->colors([
                        ProjectCharter::STATUS_DRAFT => 'gray',
                        ProjectCharter::STATUS_AWAITING_APPROVAL => 'warning',
                        ProjectCharter::STATUS_APPROVED => 'success',
                        ProjectCharter::STATUS_REJECTED => 'danger',
                        ProjectCharter::STATUS_COMPLETED => 'success',
                        ProjectCharter::STATUS_CANCELED => 'gray',
                        ProjectCharter::STATUS_SUSPENDED => 'gray',
                    ])
                    ->formatStateUsing(fn (string $state): string => __(ProjectCharter::getStatuses()[$state] ?? $state)),

                // Tables\Columns\TextColumn::make('deliverables_count')
                //     ->label(__('project_charter.deliverables_count'))
                //     ->counts('deliverables')
                //     ->badge()
                //     ->color('success'),

                // Tables\Columns\TextColumn::make('performance_card_results_count')
                //     ->label(__('project_charter.performance_card_results_count'))
                //     ->counts('performanceCardResults')
                //     ->badge()
                //     ->color('info'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('common.created_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options(ProjectCharter::getStatuses())
                    ->label(__('project_charter.status')),

                Tables\Filters\SelectFilter::make('initiative_project')
                    ->relationship('initiativeProject', 'name')
                    ->label(__('project_charter.project_charter')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\Action::make('view_progress')
                        ->label(__('project_charter.view_progress'))
                        ->icon('heroicon-o-chart-bar')
                        ->color('info')
                        ->url(fn (ProjectCharter $record): string => static::getUrl('view_progress', ['record' => $record]))
                        ->visible(fn (ProjectCharter $record) => in_array($record->status, [
                            ProjectCharter::STATUS_APPROVED,
                            ProjectCharter::STATUS_COMPLETED,
                            ProjectCharter::STATUS_CANCELED,
                            ProjectCharter::STATUS_SUSPENDED,
                        ])),
                    Tables\Actions\Action::make('manage_governance')
                        ->label(__('project_charter.manage_governance'))
                        ->icon('heroicon-o-clipboard-document-check')
                        ->color('warning')
                        ->url(fn (ProjectCharter $record): string => static::getUrl('manage_governance', ['record' => $record]))
                        ->visible(fn (ProjectCharter $record) => in_array($record->status, [
                            ProjectCharter::STATUS_APPROVED,
                            ProjectCharter::STATUS_COMPLETED,
                            ProjectCharter::STATUS_CANCELED,
                            ProjectCharter::STATUS_SUSPENDED,
                        ])),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\DeliverablesRelationManager::class,
            RelationManagers\TasksRelationManager::class,
            RelationManagers\CompletionRequestsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjectCharters::route('/'),
            'create' => Pages\CreateProjectCharter::route('/create'),
            'view' => Pages\ViewProjectCharter::route('/{record}'),
            'edit' => Pages\EditProjectCharter::route('/{record}/edit'),
            'view_progress' => Pages\ViewProgressProjectCharter::route('/{record}/progress'),
            'manage_governance' => Pages\ManageProjectGovernance::route('/{record}/governance'),
            'manage_risk_registers' => Pages\ManageRiskRegisters::route('/{record}/risk-registers'),
            'manage_files' => Pages\ManageProjectCharterFiles::route('/{record}/files'),
        ];
    }

    public static function getRecordSubNavigation(Page $page): array
    {
        $navigationItems = [
            Pages\ViewProjectCharter::class,
        ];

        // Only show progress and risk management for approved, completed, and canceled charters
        if (in_array($page->getRecord()->status, [
            ProjectCharter::STATUS_APPROVED,
            ProjectCharter::STATUS_COMPLETED,
            ProjectCharter::STATUS_CANCELED,
            ProjectCharter::STATUS_SUSPENDED,
        ])) {
            $navigationItems[] = Pages\ViewProgressProjectCharter::class;
            $navigationItems[] = Pages\ManageProjectGovernance::class;
            $navigationItems[] = Pages\ManageRiskRegisters::class;
        }

        // Files management is available for all statuses
        $navigationItems[] = Pages\ManageProjectCharterFiles::class;

        return $page->generateNavigationItems($navigationItems);
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',

            'submit_for_approval',
            'approve',
            'reject',
            'send_back_to_draft',
            'request_closure',

            // Deliverables permissions
            'approve_deliverable_file',
            'delete_after_approval_deliverable',
        ];
    }
}
