<?php

namespace App\Filament\Resources\InitiativeResource\Pages;

use App\Filament\Resources\InitiativeResource;
use App\Models\Initiative;
use App\Models\InitiativeOperationGoal;
use Filament\Actions;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\Split;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Infolists\Infolist;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Support\HtmlString;

class ViewInitiative extends ViewRecord
{
    protected static string $resource = InitiativeResource::class;

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

    protected function getInfolistActions(): array
    {
        return [
            $this->editGoalAction(),
            $this->deleteGoalAction(),
            $this->editResultAction(),
            $this->deleteResultAction(),
        ];
    }

    public function editGoalAction(): Actions\Action
    {
        return Actions\Action::make('editGoal')
            ->form([
                \Filament\Forms\Components\TextInput::make('name')
                    ->label(__('initiative_operation_goal.name'))
                    ->required()
                    ->maxLength(255),

                \Filament\Forms\Components\TextInput::make('performance_criteria')
                    ->label(__('initiative_operation_goal.performance_criteria'))
                    ->required()
                    ->maxLength(1000),

                \Filament\Forms\Components\TextInput::make('target')
                    ->label(__('initiative_operation_goal.target'))
                    ->required()
                    ->maxLength(500),

                \Filament\Forms\Components\TextInput::make('actual')
                    ->label(__('initiative_operation_goal.actual'))
                    ->maxLength(500),
            ])
            ->fillForm(function (array $arguments): array {
                $goal = InitiativeOperationGoal::find($arguments['goal']);

                return [
                    'name' => $goal->name,
                    'performance_criteria' => $goal->performance_criteria,
                    'target' => $goal->target,
                    'actual' => $goal->actual,
                ];
            })
            ->action(function (array $data, array $arguments): void {
                $goal = InitiativeOperationGoal::find($arguments['goal']);
                $goal->update($data);

                \Filament\Notifications\Notification::make()
                    ->title(__('initiative_operation_goal.updated_successfully'))
                    ->success()
                    ->send();

                // Refresh the record to show updated data
                $this->record->refresh();
            })
            ->modalHeading(__('initiative_operation_goal.edit_goal'))
            ->modalSubmitActionLabel(__('filament-actions::edit.single.modal.actions.save.label'));
    }

    public function deleteGoalAction(): Actions\Action
    {
        return Actions\Action::make('deleteGoal')
            ->requiresConfirmation()
            ->action(function (array $arguments): void {
                $goal = InitiativeOperationGoal::find($arguments['goal']);
                $goal->delete();

                \Filament\Notifications\Notification::make()
                    ->title(__('initiative_operation_goal.deleted_successfully'))
                    ->success()
                    ->send();

                // Refresh the record to show updated data
                $this->record->refresh();
            })
            ->modalHeading(__('filament-actions::delete.single.modal.heading', ['label' => __('initiative_operation_goal.operation_goal')]))
            ->modalSubmitActionLabel(__('filament-actions::delete.single.modal.actions.delete.label'))
            ->color('danger');
    }

    public function editResultAction(): Actions\Action
    {
        return Actions\Action::make('editResult')
            ->form([
                \Filament\Forms\Components\Section::make(__('initiative_result.quarterly_targets'))
                    ->schema([
                        \Filament\Forms\Components\Grid::make(2)
                            ->schema([
                                \Filament\Forms\Components\TextInput::make('expected_q1')
                                    ->label(__('initiative_result.expected_q1'))
                                    ->numeric()
                                    ->step(0.01),
                                \Filament\Forms\Components\TextInput::make('actual_q1')
                                    ->label(__('initiative_result.actual_q1'))
                                    ->numeric()
                                    ->step(0.01),
                            ]),
                        \Filament\Forms\Components\Grid::make(2)
                            ->schema([
                                \Filament\Forms\Components\TextInput::make('expected_q2')
                                    ->label(__('initiative_result.expected_q2'))
                                    ->numeric()
                                    ->step(0.01),
                                \Filament\Forms\Components\TextInput::make('actual_q2')
                                    ->label(__('initiative_result.actual_q2'))
                                    ->numeric()
                                    ->step(0.01),
                            ]),
                        \Filament\Forms\Components\Grid::make(2)
                            ->schema([
                                \Filament\Forms\Components\TextInput::make('expected_q3')
                                    ->label(__('initiative_result.expected_q3'))
                                    ->numeric()
                                    ->step(0.01),
                                \Filament\Forms\Components\TextInput::make('actual_q3')
                                    ->label(__('initiative_result.actual_q3'))
                                    ->numeric()
                                    ->step(0.01),
                            ]),
                        \Filament\Forms\Components\Grid::make(2)
                            ->schema([
                                \Filament\Forms\Components\TextInput::make('expected_q4')
                                    ->label(__('initiative_result.expected_q4'))
                                    ->numeric()
                                    ->step(0.01),
                                \Filament\Forms\Components\TextInput::make('actual_q4')
                                    ->label(__('initiative_result.actual_q4'))
                                    ->numeric()
                                    ->step(0.01),
                            ]),
                    ]),

                \Filament\Forms\Components\Select::make('performanceCardResults')
                    ->label(__('initiative_result.performance_card_results'))
                    ->multiple()
                    ->options(function () {
                        $initiative = $this->record;
                        if (! $initiative || ! $initiative->performanceWallet || ! $initiative->performanceWallet->performance_card_id) {
                            return [];
                        }

                        return \App\Models\PerformanceCardResult::where('performance_card_id', $initiative->performanceWallet->performance_card_id)
                            ->with('performanceCard')
                            ->get()
                            ->mapWithKeys(function ($result) {
                                return [$result->id => $result->performanceCard->goal.' - '.$result->result];
                            });
                    })
                    ->searchable()
                    ->helperText(function () {
                        $initiative = $this->record;
                        if (! $initiative || ! $initiative->performanceWallet) {
                            return __('initiative_result.no_wallet_assigned');
                        }

                        return __('initiative_result.performance_card_results_helper');
                    })
                    ->disabled(function () {
                        $initiative = $this->record;

                        return ! $initiative || ! $initiative->performanceWallet;
                    }),
            ])
            ->fillForm(function (array $arguments): array {
                $result = $this->record->results()->find($arguments['result']);

                return [
                    'expected_q1' => $result->expected_q1,
                    'actual_q1' => $result->actual_q1,
                    'expected_q2' => $result->expected_q2,
                    'actual_q2' => $result->actual_q2,
                    'expected_q3' => $result->expected_q3,
                    'actual_q3' => $result->actual_q3,
                    'expected_q4' => $result->expected_q4,
                    'actual_q4' => $result->actual_q4,
                    'performanceCardResults' => $result->performanceCardResults->pluck('id')->toArray(),
                ];
            })
            ->action(function (array $data, array $arguments): void {
                $result = $this->record->results()->find($arguments['result']);
                $performanceCardResults = $data['performanceCardResults'] ?? [];
                unset($data['performanceCardResults']);

                $result->update($data);
                $result->performanceCardResults()->sync($performanceCardResults);

                \Filament\Notifications\Notification::make()
                    ->title(__('initiative_result.updated_successfully'))
                    ->success()
                    ->send();

                // Refresh the record to show updated data
                $this->record->refresh();
            })
            ->modalHeading(__('initiative_result.edit_result'))
            ->modalSubmitActionLabel(__('filament-actions::edit.single.modal.actions.save.label'));
    }

    public function deleteResultAction(): Actions\Action
    {
        return Actions\Action::make('deleteResult')
            ->requiresConfirmation()
            ->action(function (array $arguments): void {
                $result = $this->record->results()->find($arguments['result']);
                $result->delete();

                \Filament\Notifications\Notification::make()
                    ->title(__('initiative_result.deleted_successfully'))
                    ->success()
                    ->send();

                // Refresh the record to show updated data
                $this->record->refresh();
            })
            ->modalHeading(__('filament-actions::delete.single.modal.heading', ['label' => __('initiative_result.initiative_result')]))
            ->modalSubmitActionLabel(__('filament-actions::delete.single.modal.actions.delete.label'))
            ->color('danger');
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Grid::make(1)
                    ->schema([
                        $this->getInitiativeInfoSplit(),
                    ]),
            ]);
    }

    public function getInitiativeInfoSplit(): Split
    {
        return Split::make([
            // Right Column - Initiative Information
            Grid::make(1)
                ->schema([
                    // Initiative Information
                    Section::make(__('initiative.initiative_information'))
                        ->icon('heroicon-o-rocket-launch')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('id')
                                        ->label(__('initiative.initiative_number'))
                                        ->weight(FontWeight::SemiBold)
                                        ->color('gray')
                                        ->badge()
                                        ->prefix('#'),

                                    TextEntry::make('name')
                                        ->label(__('initiative.name'))
                                        ->weight(FontWeight::SemiBold)
                                        ->icon('heroicon-o-rocket-launch'),

                                    TextEntry::make('start_date')
                                        ->label(__('initiative.start_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar-days')
                                        ->color('success'),

                                    TextEntry::make('expected_end_date')
                                        ->label(__('initiative.expected_end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar')
                                        ->color('warning'),

                                    TextEntry::make('performanceCard.department.name')
                                        ->label(__('initiative.department'))
                                        ->icon('heroicon-o-building-office')
                                        ->color('primary'),
                                ]),

                            TextEntry::make('description')
                                ->label(__('initiative.description'))
                                ->html()
                                ->columnSpanFull()
                                ->placeholder(__('initiative.no_description')),

                            TextEntry::make('products.name')
                                ->label(__('initiative.products'))
                                ->badge()
                                ->color('gray')
                                ->separator(' ')
                                ->columnSpanFull()
                                ->placeholder(__('initiative.no_products')),
                        ]),

                    // Operation Goals Section
                    Section::make(__('initiative_operation_goal.operation_goals'))
                        ->icon('heroicon-o-flag')
                        ->headerActions([
                            \Filament\Infolists\Components\Actions\Action::make('add_goal')
                                ->label(__('initiative_operation_goal.add_goal'))
                                ->icon('heroicon-o-plus-circle')
                                ->color('success')
                                ->form([
                                    \Filament\Forms\Components\TextInput::make('name')
                                        ->label(__('initiative_operation_goal.name'))
                                        ->required()
                                        ->maxLength(255)
                                        ->helperText(__('initiative_operation_goal.name_helper')),

                                    \Filament\Forms\Components\TextInput::make('performance_criteria')
                                        ->label(__('initiative_operation_goal.performance_criteria'))
                                        ->required()
                                        ->maxLength(1000)
                                        ->helperText(__('initiative_operation_goal.performance_criteria_helper')),

                                    \Filament\Forms\Components\TextInput::make('target')
                                        ->label(__('initiative_operation_goal.target'))
                                        ->required()
                                        ->maxLength(500)
                                        ->helperText(__('initiative_operation_goal.target_helper')),

                                    \Filament\Forms\Components\TextInput::make('actual')
                                        ->label(__('initiative_operation_goal.actual'))
                                        ->maxLength(500)
                                        ->helperText(__('initiative_operation_goal.actual_helper')),
                                ])
                                ->action(function (array $data): void {
                                    $this->record->operationGoals()->create($data);

                                    \Filament\Notifications\Notification::make()
                                        ->title(__('initiative_operation_goal.created_successfully'))
                                        ->success()
                                        ->send();

                                    // Refresh the page to show the new goal
                                    $this->redirect(request()->header('Referer'));
                                })
                                ->modalHeading(__('initiative_operation_goal.add_goal'))
                                ->modalSubmitActionLabel(__('filament-actions::create.single.modal.actions.create.label')),
                        ])
                        ->schema([
                            ViewEntry::make('goals')
                                ->view('filament.infolists.entries.goal')
                                ->columnSpanFull(),
                        ]),

                ]),

            // Left Column - Initiative Determinants & Operational Indicators
            Grid::make(1)
                ->schema([
                    // Initiative Determinants
                    Section::make(__('initiative.initiative_determinants'))
                        ->icon('heroicon-o-calculator')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('expected_cost')
                                        ->label(__('initiative.estimated_cost'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-banknotes')
                                        ->color('primary'),

                                    TextEntry::make('actual_cost')
                                        ->label(__('initiative.actual_cost'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-currency-dollar')
                                        ->color('success'),

                                    TextEntry::make('emergency_reserve')
                                        ->label(__('initiative.emergency_reserve'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-shield-check')
                                        ->color('warning'),

                                    TextEntry::make('reserve_status')
                                        ->label(__('initiative.reserve_status'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-information-circle')
                                        ->color('gray'),

                                    TextEntry::make('estimated_budget')
                                        ->label(__('initiative.estimated_budget'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-chart-pie')
                                        ->color('info'),

                                    TextEntry::make('total_expenses')
                                        ->label(__('initiative.total_expenses'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-receipt-percent')
                                        ->color('danger'),
                                ]),
                        ]),

                    // Operational Indicators
                    Section::make(__('initiative.operational_indicators'))
                        ->icon('heroicon-o-chart-bar-square')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('overall_progress')
                                        ->label(__('initiative.technical_completion_percentage'))
                                        // ->formatStateUsing(fn() => '0')
                                        ->suffix('%')
                                        ->icon('heroicon-o-cog')
                                        ->color('primary')
                                        ->weight(FontWeight::Bold),

                                    TextEntry::make('financial_completion_percentage')
                                        ->label(__('initiative.financial_completion_percentage'))
                                        ->suffix('%')
                                        ->icon('heroicon-o-currency-dollar')
                                        ->color('success')
                                        ->weight(FontWeight::Bold),
                                ]),
                        ]),

                    // Initiative Results Section
                    Section::make(__('initiative_result.initiative_results'))
                        ->icon('heroicon-o-chart-bar')
                        ->headerActions([
                            \Filament\Infolists\Components\Actions\Action::make('add_result')
                                ->label(__('initiative_result.initiative_results'))
                                ->icon('heroicon-o-plus-circle')
                                ->color('success')
                                ->form([
                                    \Filament\Forms\Components\Section::make(__('initiative_result.quarterly_targets'))
                                        ->schema([
                                            \Filament\Forms\Components\Grid::make(2)
                                                ->schema([
                                                    \Filament\Forms\Components\TextInput::make('expected_q1')
                                                        ->label(__('initiative_result.expected_q1'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                    \Filament\Forms\Components\TextInput::make('actual_q1')
                                                        ->label(__('initiative_result.actual_q1'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                ]),
                                            \Filament\Forms\Components\Grid::make(2)
                                                ->schema([
                                                    \Filament\Forms\Components\TextInput::make('expected_q2')
                                                        ->label(__('initiative_result.expected_q2'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                    \Filament\Forms\Components\TextInput::make('actual_q2')
                                                        ->label(__('initiative_result.actual_q2'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                ]),
                                            \Filament\Forms\Components\Grid::make(2)
                                                ->schema([
                                                    \Filament\Forms\Components\TextInput::make('expected_q3')
                                                        ->label(__('initiative_result.expected_q3'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                    \Filament\Forms\Components\TextInput::make('actual_q3')
                                                        ->label(__('initiative_result.actual_q3'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                ]),
                                            \Filament\Forms\Components\Grid::make(2)
                                                ->schema([
                                                    \Filament\Forms\Components\TextInput::make('expected_q4')
                                                        ->label(__('initiative_result.expected_q4'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                    \Filament\Forms\Components\TextInput::make('actual_q4')
                                                        ->label(__('initiative_result.actual_q4'))
                                                        ->numeric()
                                                        ->step(0.01),
                                                ]),
                                        ]),

                                    \Filament\Forms\Components\Select::make('performanceCardResults')
                                        ->label(__('initiative_result.performance_card_results'))
                                        ->multiple()
                                        ->options(function () {
                                            $initiative = $this->record;
                                            if (! $initiative || ! $initiative->performanceWallet || ! $initiative->performanceWallet->performance_card_id) {
                                                return [];
                                            }

                                            return \App\Models\PerformanceCardResult::where('performance_card_id', $initiative->performanceWallet->performance_card_id)
                                                ->with('performanceCard')
                                                ->get()
                                                ->mapWithKeys(function ($result) {
                                                    return [$result->id => $result->performanceCard->goal.' - '.$result->result];
                                                });
                                        })
                                        ->searchable()
                                        ->helperText(function () {
                                            $initiative = $this->record;
                                            if (! $initiative || ! $initiative->performanceWallet) {
                                                return __('initiative_result.no_wallet_assigned');
                                            }

                                            return __('initiative_result.performance_card_results_helper');
                                        })
                                        ->disabled(function () {
                                            $initiative = $this->record;

                                            return ! $initiative || ! $initiative->performanceWallet;
                                        }),
                                ])
                                ->action(function (array $data): void {
                                    $performanceCardResults = $data['performanceCardResults'] ?? [];
                                    unset($data['performanceCardResults']);

                                    $result = $this->record->results()->create($data);

                                    if (! empty($performanceCardResults)) {
                                        $result->performanceCardResults()->sync($performanceCardResults);
                                    }

                                    \Filament\Notifications\Notification::make()
                                        ->title(__('initiative_result.created_successfully'))
                                        ->success()
                                        ->send();

                                    // Refresh the page to show the new result
                                    $this->redirect(request()->header('Referer'));
                                })
                                ->modalHeading(__('initiative_result.initiative_results'))
                                ->modalSubmitActionLabel(__('filament-actions::create.single.modal.actions.create.label')),
                        ])
                        ->schema([
                            ViewEntry::make('results')
                                ->view('filament.infolists.entries.result')
                                ->columnSpanFull(),
                        ]),
                ]),
        ])
            ->from('lg')
            ->columnSpan('full');
    }
}
