<?php

namespace App\Filament\Resources\ProjectCharterResource\Pages;

use App\Filament\Resources\OrderResource;
use App\Filament\Resources\ProjectCharterResource;
use App\Filament\Resources\ServiceProviderResource;
use App\Models\Order;
use App\Models\ProjectCharter;
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\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class ViewProjectCharter extends ViewRecord
{
    protected static string $resource = ProjectCharterResource::class;

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

    protected function getHeaderActions(): array
    {
        $actions = [];
        $record = $this->getRecord();

        // Only allow editing if status is draft
        if ($record->canEdit()) {
            $actions[] = Actions\EditAction::make();
        }

        // Submit for approval action (draft -> awaiting_approval)
        if ($record->canSubmitForApproval() && Auth::user()->can('submit_for_approval_project::charter')) {
            $actions[] = Actions\Action::make('submit_for_approval')
                ->label(__('project_charter.submit_for_approval'))
                ->icon('heroicon-o-paper-airplane')
                ->color('warning')
                ->form([
                    Forms\Components\Textarea::make('notes')
                        ->label(__('project_charter.submission_notes'))
                        ->rows(3)
                        ->placeholder(__('project_charter.submission_notes_placeholder')),
                ])
                ->action(function (array $data) use ($record) {
                    if ($record->submitForApproval($data['notes'] ?? '')) {
                        Notification::make()
                            ->title(__('project_charter.submitted_for_approval_successfully'))
                            ->success()
                            ->send();

                        return redirect(ProjectCharterResource::getUrl('view', ['record' => $record]));
                    } else {
                        Notification::make()
                            ->title(__('project_charter.submission_failed'))
                            ->danger()
                            ->send();
                    }
                });
        }

        // Approve action (awaiting_approval -> approved)
        if ($record->canApprove() && Auth::user()->can('approve_project::charter')) {
            $actions[] = Actions\Action::make('approve')
                ->label(__('project_charter.approve'))
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->form([
                    Forms\Components\Textarea::make('notes')
                        ->label(__('project_charter.approval_notes'))
                        ->rows(3)
                        ->placeholder(__('project_charter.approval_notes_placeholder')),
                ])
                ->action(function (array $data) use ($record) {
                    if ($record->approve($data['notes'] ?? '')) {
                        Notification::make()
                            ->title(__('project_charter.approved_successfully'))
                            ->success()
                            ->send();

                        return redirect(ProjectCharterResource::getUrl('view', ['record' => $record]));
                    } else {
                        Notification::make()
                            ->title(__('project_charter.approval_failed'))
                            ->danger()
                            ->send();
                    }
                });
        }

        // Reject action (awaiting_approval -> rejected)
        if ($record->canReject() && Auth::user()->can('reject_project::charter')) {
            $actions[] = Actions\Action::make('reject')
                ->label(__('project_charter.reject'))
                ->icon('heroicon-o-x-circle')
                ->color('danger')
                ->form([
                    Forms\Components\Textarea::make('notes')
                        ->label(__('project_charter.rejection_notes'))
                        ->required()
                        ->rows(3)
                        ->placeholder(__('project_charter.rejection_notes_placeholder')),
                ])
                ->action(function (array $data) use ($record) {
                    if ($record->reject($data['notes'])) {
                        Notification::make()
                            ->title(__('project_charter.rejected_successfully'))
                            ->success()
                            ->send();

                        return redirect(ProjectCharterResource::getUrl('view', ['record' => $record]));
                    } else {
                        Notification::make()
                            ->title(__('project_charter.rejection_failed'))
                            ->danger()
                            ->send();
                    }
                });
        }

        // Send back to draft action (awaiting_approval -> draft)
        if ($record->canSendBackToDraft() && Auth::user()->can('send_back_to_draft_project::charter')) {
            $actions[] = Actions\Action::make('send_back_to_draft')
                ->label(__('project_charter.send_back_to_draft'))
                ->icon('heroicon-o-arrow-left-circle')
                ->color('gray')
                ->form([
                    Forms\Components\Textarea::make('notes')
                        ->label(__('project_charter.send_back_notes'))
                        ->rows(3)
                        ->placeholder(__('project_charter.send_back_notes_placeholder')),
                ])
                ->action(function (array $data) use ($record) {
                    if ($record->sendBackToDraft($data['notes'] ?? '')) {
                        Notification::make()
                            ->title(__('project_charter.sent_back_to_draft_successfully'))
                            ->success()
                            ->send();

                        return redirect(ProjectCharterResource::getUrl('view', ['record' => $record]));
                    } else {
                        Notification::make()
                            ->title(__('project_charter.send_back_failed'))
                            ->danger()
                            ->send();
                    }
                });
        }

        $actions[] = Actions\DeleteAction::make()
            ->visible(fn () => $record->canEdit()); // Only allow deletion if draft

        return $actions;
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                $this->getProjectCharterInfoSplit(),
            ]);
    }

    public function getProjectCharterInfoSplit(): Split
    {
        return Split::make([
            // Left Column - Charter Overview
            Grid::make(1)
                ->schema([
                    // Charter Overview Card
                    Section::make(__('project_charter.charter_overview'))
                        ->icon('heroicon-o-document-text')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('id')
                                        ->label(__('project_charter.charter_id'))
                                        ->weight(FontWeight::SemiBold)
                                        ->color('gray')
                                        ->badge()
                                        ->formatStateUsing(function ($state, $record) {
                                            $projectManner = $record->project_manner;
                                            if ($projectManner) {
                                                return strtoupper(substr($projectManner, 0, 1)).'-'.$state;
                                            }
                                            return '#'.$state;
                                        }),

                                    TextEntry::make('status')
                                        ->label(__('project_charter.status'))
                                        ->badge()
                                        ->formatStateUsing(fn (string $state): string => ProjectCharter::getStatuses()[$state] ?? $state)
                                        ->color(fn (string $state): string => match ($state) {
                                            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',
                                            default => 'gray',
                                        }),

                                    TextEntry::make('name')
                                        ->label(__('project_charter.name'))
                                        ->weight(FontWeight::SemiBold)
                                        ->icon('heroicon-o-document-text'),

                                    TextEntry::make('initiativeProject.initiative.performanceCard.project_manner')
                                        ->label(__('project_charter.project_manner'))
                                        ->state(fn ($record) => $record->project_manner)
                                        ->formatStateUsing(fn ($state) => $state ?
                                            \App\Models\PerformanceCard::getProjectManners()[$state] ?? $state : '-')
                                        ->badge()
                                        ->color(fn ($state): string => match ($state) {
                                            \App\Models\PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL => 'success',
                                            \App\Models\PerformanceCard::PROJECT_MANNER_SUPPORT => 'info',
                                            \App\Models\PerformanceCard::PROJECT_MANNER_EMPOWERMENT => 'warning',
                                            \App\Models\PerformanceCard::PROJECT_MANNER_INVESTMENT => 'primary',
                                            default => 'gray',
                                        })
                                        ->placeholder('-'),
                                ]),

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

                        ]),

                    // Project Relationships Card
                    Section::make(__('project_charter.project_relationships'))
                        ->icon('heroicon-o-link')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('initiativeProject.name')
                                        ->label(__('project_charter.initiative_project'))
                                        ->weight(FontWeight::Medium)
                                        ->icon('heroicon-o-rocket-launch')
                                        ->color('primary'),

                                    TextEntry::make('order.id')
                                        ->label(__('project_charter.linked_order'))
                                        ->formatStateUsing(fn ($record) => $record->order ?
                                            "#{$record->order->id} - ".Order::getOrderTypes()[$record->order->type] : '-')
                                        ->url(fn ($record) => $record->order ? OrderResource::getUrl('view', ['record' => $record->order]) : null)
                                        ->openUrlInNewTab(false)
                                        ->icon('heroicon-o-document-duplicate')
                                        ->color('info')
                                        ->placeholder('-'),

                                    TextEntry::make('initiativeProject.initiative.name')
                                        ->label(__('project_charter.initiative'))
                                        ->icon('heroicon-o-light-bulb')
                                        ->color('warning'),

                                    TextEntry::make('initiativeProject.initiative.performanceCard.department.name')
                                        ->label(__('project_charter.department'))
                                        ->icon('heroicon-o-building-office')
                                        ->color('success')
                                        ->placeholder('-'),

                                    // service provider if exists
                                    TextEntry::make('serviceProvider.name')
                                        ->label(__('service_provider.service_provider'))
                                        ->icon('heroicon-o-user')
                                        ->color('primary')
                                        ->placeholder('-'),
                                    // ->url(fn($record) => $record->serviceProvider ? ServiceProviderResource::getUrl('view', ['record' => $record->serviceProvider]) : null),
                                ]),
                        ]),
                ]),

            // Right Column - Timeline & Financial Information
            Grid::make(1)
                ->schema([
                    // Timeline Card
                    Section::make(__('project_charter.timeline'))
                        ->icon('heroicon-o-calendar-days')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('start_date')
                                        ->label(__('project_charter.start_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar-days')
                                        ->color('success')
                                        ->weight(FontWeight::Medium),

                                    TextEntry::make('expected_end_date')
                                        ->label(__('project_charter.expected_end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar')
                                        ->color('warning')
                                        ->weight(FontWeight::Medium),
                                ]),

                            // Duration calculation
                            TextEntry::make('duration')
                                ->label(__('project_charter.duration'))
                                ->state(function ($record) {
                                    if (! $record->start_date || ! $record->expected_end_date) {
                                        return '-';
                                    }
                                    $duration = $record->start_date->diffInDays($record->expected_end_date);

                                    return __('project_charter.duration_days', ['days' => $duration]);
                                })
                                ->icon('heroicon-o-clock')
                                ->color('info')
                                ->columnSpanFull(),
                        ]),

                    // Financial Information Card
                    Section::make(__('project_charter.financial_information'))
                        ->icon('heroicon-o-banknotes')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('estimated_cost')
                                        ->label(__('project_charter.estimated_cost'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-calculator')
                                        ->color('primary')
                                        ->weight(FontWeight::Medium),

                                    TextEntry::make('total_cost')
                                        ->label(__('project_charter.total_cost'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-banknotes')
                                        ->color('success')
                                        ->weight(FontWeight::Bold),
                                ]),

                            // // Cost difference calculation
                            // TextEntry::make('cost_difference')
                            //     ->label(__('project_charter.cost_difference'))
                            //     ->formatStateUsing(function ($record) {
                            //         if (!$record->estimated_cost || !$record->total_cost) {
                            //             return '-';
                            //         }
                            //         $difference = $record->total_cost - $record->estimated_cost;
                            //         $percentage = ($difference / $record->estimated_cost) * 100;

                            //         $sign = $difference >= 0 ? '+' : '';
                            //         $color = $difference >= 0 ? 'text-red-600' : 'text-green-600';

                            //         return new HtmlString(
                            //             '<span class="' . $color . ' font-medium">' .
                            //                 $sign . '$' . number_format($difference, 2) .
                            //                 ' (' . $sign . number_format($percentage, 1) . '%)</span>'
                            //         );
                            //     })
                            //     ->icon('heroicon-o-calculator')
                            //     ->columnSpanFull(),
                        ]),

                    // Performance Tracking Card
                    // Section::make(__('project_charter.performance_tracking'))
                    //     ->icon('heroicon-o-chart-bar')
                    //     ->schema([
                    //         TextEntry::make('deliverables_count')
                    //             ->label(__('project_charter.deliverables_count'))
                    //             ->formatStateUsing(fn($record) => $record->deliverables()->count())
                    //             ->badge()
                    //             ->color('success')
                    //             ->icon('heroicon-o-check-circle'),

                    //         TextEntry::make('performance_card_results_count')
                    //             ->label(__('project_charter.performance_card_results_count'))
                    //             ->formatStateUsing(fn($record) => $record->performanceCardResults()->count())
                    //             ->badge()
                    //             ->color('info')
                    //             ->icon('heroicon-o-chart-bar'),

                    //         TextEntry::make('progress_status')
                    //             ->label(__('project_charter.progress_status'))
                    //             ->formatStateUsing(function ($record) {
                    //                 $deliverables = $record->deliverables()->count();
                    //                 $results = $record->performanceCardResults()->count();

                    //                 if ($deliverables === 0 && $results === 0) {
                    //                     return __('project_charter.not_started');
                    //                 } elseif ($deliverables > 0 || $results > 0) {
                    //                     return __('project_charter.in_progress');
                    //                 }

                    //                 return __('project_charter.pending');
                    //             })
                    //             ->badge()
                    //             ->color(function ($record) {
                    //                 $deliverables = $record->deliverables()->count();
                    //                 $results = $record->performanceCardResults()->count();

                    //                 if ($deliverables === 0 && $results === 0) {
                    //                     return 'gray';
                    //                 } elseif ($deliverables > 0 || $results > 0) {
                    //                     return 'warning';
                    //                 }

                    //                 return 'info';
                    //             })
                    //             ->icon('heroicon-o-information-circle')
                    //             ->columnSpanFull(),
                    //     ]),
                ]),
        ])
            ->from('lg')
            ->columnSpan('full');
    }

    protected function getAllRelationManagers(): array
    {
        return [];
    }
}
