<?php

namespace App\Filament\Resources\PerformanceCardResource\Pages;

use App\Filament\Resources\PerformanceCardResource;
use App\Models\PerformanceWallet;
use Filament\Actions;
use Filament\Forms;
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 ViewWalletPerformanceCard extends ViewRecord
{
    protected static string $resource = PerformanceCardResource::class;

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

    protected function getHeaderActions(): array
    {
        return [
            $this->getWalletAction(),
        ];
    }

    protected function getWalletAction(): Actions\Action
    {
        $hasWallet = $this->record->wallet !== null;

        return Actions\Action::make('manage_wallet')
            ->label($hasWallet ? __('performance_wallet.edit_wallet') : __('performance_wallet.create_wallet'))
            ->icon($hasWallet ? 'heroicon-o-pencil-square' : 'heroicon-o-plus-circle')
            ->color($hasWallet ? 'warning' : 'success')
            ->form($this->getWalletForm())
            ->fillForm(function (): array {
                if ($this->record->wallet) {
                    return [
                        'name' => $this->record->wallet->name,
                        'start_date' => $this->record->wallet->start_date,
                        'expected_end_date' => $this->record->wallet->expected_end_date,
                        'description' => $this->record->wallet->description,
                    ];
                }

                return [];
            })
            ->action(function (array $data): void {
                if ($this->record->wallet) {
                    // Update existing wallet
                    $this->record->wallet->update($data);
                    \Filament\Notifications\Notification::make()
                        ->title(__('performance_wallet.updated_successfully'))
                        ->success()
                        ->send();
                } else {
                    // Create new wallet
                    $data['performance_card_id'] = $this->record->id;
                    PerformanceWallet::create($data);
                    \Filament\Notifications\Notification::make()
                        ->title(__('performance_wallet.created_successfully'))
                        ->success()
                        ->send();
                }

                // Refresh the record to show updated wallet information
                $this->record->refresh();
            })
            ->modalHeading($hasWallet ? __('performance_wallet.edit_wallet') : __('performance_wallet.create_wallet'))
            ->modalSubmitActionLabel($hasWallet ? __('filament-actions::edit.single.modal.actions.save.label') : __('filament-actions::create.single.modal.actions.create.label'));
    }

    protected function getWalletForm(): array
    {
        return [
            Forms\Components\TextInput::make('name')
                ->label(__('performance_wallet.name'))
                ->required()
                ->maxLength(255)
                ->helperText(__('performance_wallet.name_helper')),

            Forms\Components\DatePicker::make('start_date')
                ->label(__('performance_wallet.start_date'))
                ->required()
                ->helperText(__('performance_wallet.date_range_helper')),

            Forms\Components\DatePicker::make('expected_end_date')
                ->label(__('performance_wallet.expected_end_date'))
                ->required()
                ->after('start_date'),

            Forms\Components\Textarea::make('description')
                ->label(__('performance_wallet.description'))
                ->required()
                ->rows(4)
                ->maxLength(1000)
                ->helperText(__('performance_wallet.description_helper')),
        ];
    }

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

    public function getWalletInfoSplit(): Split
    {
        return Split::make([
            // Right Column - Wallet Results
            Grid::make(1)
                ->schema([
                    // Aggregated Initiative Results Section
                    Section::make(__('performance_card.wallet_results'))
                        ->icon('heroicon-o-chart-bar')
                        ->description(__('performance_card.aggregated_results_from_initiatives'))
                        ->schema([
                            ViewEntry::make('aggregated_results')
                                ->view('filament.infolists.entries.aggregated-results')
                                ->columnSpanFull(),
                        ]),
                ]),

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

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

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

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

                    // Wallet Information
                    Section::make(__('performance_wallet.performance_wallet'))
                        ->icon('heroicon-o-briefcase')
                        ->schema([
                            // Show wallet information if exists
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('wallet.name')
                                        ->label(__('performance_wallet.name'))
                                        ->weight(FontWeight::SemiBold)
                                        ->icon('heroicon-o-briefcase'),

                                    TextEntry::make('wallet.start_date')
                                        ->label(__('performance_wallet.start_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar-days'),

                                    TextEntry::make('wallet.expected_end_date')
                                        ->label(__('performance_wallet.expected_end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar')
                                        ->color('warning'),
                                ])
                                ->visible(fn ($record) => $record->wallet !== null),

                            TextEntry::make('wallet.description')
                                ->label(__('performance_wallet.description'))
                                ->html()
                                ->columnSpanFull()
                                ->visible(fn ($record) => $record->wallet !== null),

                            // Show message when no wallet exists
                            TextEntry::make('no_wallet_message')
                                ->label(__('performance_wallet.status'))
                                ->state(fn () => __('performance_wallet.wallet_not_found'))
                                ->color('gray')
                                ->icon('heroicon-o-exclamation-triangle')
                                ->columnSpanFull()
                                ->visible(fn ($record) => $record->wallet === null),
                        ]),
                ]),
        ])
            ->from('lg')
            ->columnSpan('full');
    }
}
