<?php

namespace App\Filament\Resources\ProjectCharterResource\Pages;

use App\Filament\Resources\ProjectCharterResource;
use App\Models\ProjectCharter;
use App\Models\ProjectCharterCompletionRequest;
use App\Utils\ProgressBarRenderer;
use Filament\Actions;
use Filament\Forms;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Infolist;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\HtmlString;

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

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

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

        // Request closure action (approved -> request_closure)
        if ($record->canRequestClosure() && Auth::user()->can('request_closure_project::charter')) {
            $actions[] = Actions\CreateAction::make()
                ->model(ProjectCharterCompletionRequest::class)
                ->label(__('project_charter.request_closure_action'))
                ->icon('heroicon-o-x-mark')
                ->color('warning')
                ->steps($this->getClosureWizardSteps($record))
                ->modalHeading(__('project_charter_completion_request.project_charter_completion_request'))
                ->mutateFormDataUsing(function (array $data) use ($record): array {
                    $data['project_charter_id'] = $record->id;
                    $data['status'] = ProjectCharterCompletionRequest::STATUS_PENDING;

                    return $data;
                })
                ->after(function (ProjectCharterCompletionRequest $completionRequest) use ($record) {
                    // Log activity
                    activity()
                        ->performedOn($record)
                        ->causedBy(Auth::user())
                        ->event('closure_requested')
                        ->withProperties([
                            'type' => $completionRequest->type,
                            'reason' => $completionRequest->reason ?? '',
                            'completion_request_id' => $completionRequest->id,
                        ])
                        ->log('Project charter closure requested');
                })
                ->successNotificationTitle(__('project_charter.closure_requested_successfully'))
                ->successRedirectUrl(fn () => ProjectCharterResource::getUrl('view_progress', ['record' => $record]));
        }

        return $actions;
    }

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

    public function getProgressSection(): Section
    {
        return Section::make(__('project_charter.project_progress'))
            ->icon('heroicon-o-chart-bar')
            ->schema([
                Grid::make(3)
                    ->schema([
                        // First Row: Phase, Status, Estimated Progress
                        TextEntry::make('project_phase')
                            ->label(__('project_charter.project_phase'))
                            ->badge()
                            ->color(fn ($record) => $record->project_phase_color),

                        TextEntry::make('project_status')
                            ->label(__('project_charter.status'))
                            ->badge()
                            ->color(fn ($record) => $record->project_status_color)
                            ->formatStateUsing(function ($state) {
                                return match ($state) {
                                    'not_started' => __('project_charter.project_status_not_started'),
                                    'in_progress' => __('project_charter.project_status_in_progress'),
                                    'late' => __('project_charter.project_status_late'),
                                    'done' => __('project_charter.project_status_done'),
                                    default => $state,
                                };
                            }),

                        TextEntry::make('estimated_progress_percentage')
                            ->label(__('project_charter.estimated_progress'))
                            ->formatStateUsing(function ($state) {
                                if (! $state) {
                                    return 'N/A';
                                }

                                return number_format($state, 1).'%';
                            })
                            ->badge()
                            ->color(fn ($record) => $record->estimated_progress_color),
                    ]),

                Grid::make(3)
                    ->schema([
                        // Second Row: Actual Progress, Financial Progress, Progress Deviation
                        TextEntry::make('project_progress')
                            ->label(__('project_charter.project_completion_percentage'))
                            ->formatStateUsing(fn (string $state): HtmlString => new HtmlString(ProgressBarRenderer::render($state, __('project_charter.project_completion_percentage')))),

                        TextEntry::make('financial_progress')
                            ->label(__('project_charter.financial_completion_percentage'))
                            ->formatStateUsing(fn (string $state): HtmlString => new HtmlString(ProgressBarRenderer::render($state, __('project_charter.financial_completion_percentage')))),

                        TextEntry::make('progress_deviation')
                            ->label(__('project_charter.progress_deviation'))
                            ->formatStateUsing(function ($state) {
                                if (! is_numeric($state)) {
                                    return 'N/A';
                                }
                                $sign = $state >= 0 ? '+' : '';

                                return $sign.number_format($state, 1).'%';
                            })
                            ->badge()
                            ->color(fn ($record) => $record->progress_deviation_color),
                    ]),
            ])
            ->columnSpanFull();
    }

    /**
     * Get the wizard steps for the closure action
     *
     * @return array<Forms\Components\Wizard\Step>
     */
    protected function getClosureWizardSteps(ProjectCharter $record): array
    {
        return [
            $this->getClosureTypeStep($record),
            $this->getProjectSummaryStep($record),
        ];
    }

    /**
     * Get the first step of the closure wizard (type and reason)
     */
    protected function getClosureTypeStep(ProjectCharter $record): Forms\Components\Wizard\Step
    {
        return Forms\Components\Wizard\Step::make('closure_type')
            ->label(__('project_charter.closure_type_step'))
            ->description(__('project_charter.closure_type_step_description'))
            ->schema([
                $this->getClosureTypeSelect($record),
                $this->getClosureReasonTextarea($record),
            ]);
    }

    /**
     * Get the closure type select component
     */
    protected function getClosureTypeSelect(ProjectCharter $record): Forms\Components\Select
    {
        return Forms\Components\Select::make('type')
            ->label(__('project_charter.request_closure_action'))
            ->options(function () use ($record) {
                $options = ProjectCharterCompletionRequest::getTypes();

                // Remove completion option if progress is not 100%
                if (! $this->isProjectFullyCompleted($record)) {
                    unset($options[ProjectCharterCompletionRequest::TYPE_COMPLETE]);
                }

                return $options;
            })
            ->required()
            ->live()
            ->default(function () use ($record) {
                return $this->isProjectFullyCompleted($record)
                    ? ProjectCharterCompletionRequest::TYPE_COMPLETE
                    : ProjectCharterCompletionRequest::TYPE_CANCEL;
            })
            ->helperText(function () use ($record) {
                if (! $this->isProjectFullyCompleted($record)) {
                    $projectProgress = $record->project_progress ?? 0;
                    $financialProgress = $record->financial_progress ?? 0;

                    return __('project_charter.completion_not_available_helper', [
                        'project_progress' => number_format($projectProgress, 1),
                        'financial_progress' => number_format($financialProgress, 1),
                    ]);
                }

                return null;
            });
    }

    /**
     * Get the closure reason textarea component
     */
    protected function getClosureReasonTextarea(ProjectCharter $record): Forms\Components\Textarea
    {
        return Forms\Components\Textarea::make('reason')
            ->label(__('project_charter.closure_reason'))
            ->required(fn ($get) => $get('type') !== ProjectCharterCompletionRequest::TYPE_COMPLETE)
            ->rows(4)
            ->placeholder(__('project_charter.closure_reason_placeholder'))
            ->hidden(fn ($get) => $get('type') === ProjectCharterCompletionRequest::TYPE_COMPLETE);
    }

    /**
     * Check if the project is fully completed (both progress and financial at 100%)
     */
    protected function isProjectFullyCompleted(ProjectCharter $record): bool
    {
        $projectProgress = $record->project_progress ?? 0;
        $financialProgress = $record->financial_progress ?? 0;

        return $projectProgress >= 100 && $financialProgress >= 100;
    }

    /**
     * Get the second step of the closure wizard (project summary and details)
     */
    protected function getProjectSummaryStep(ProjectCharter $record): Forms\Components\Wizard\Step
    {
        return Forms\Components\Wizard\Step::make('project_summary')
            ->label(__('project_charter.project_summary_step'))
            ->description(__('project_charter.project_summary_step_description'))
            ->schema([
                $this->getCharterOverviewSection($record),
                $this->getTimelineAndFinancialSection($record),
                $this->getProgressAndPerformanceSection($record),
                $this->getClosureDetailsSection(),
            ]);
    }

    /**
     * Get the charter overview section with read-only information
     */
    protected function getCharterOverviewSection(ProjectCharter $record): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter.charter_overview'))
            ->icon('heroicon-o-document-text')
            ->schema([
                Forms\Components\Grid::make(2)
                    ->schema([
                        Forms\Components\Placeholder::make('charter_id')
                            ->label(__('project_charter.charter_id'))
                            ->content(fn () => "#{$record->id}"),

                        Forms\Components\Placeholder::make('status')
                            ->label(__('project_charter.status'))
                            ->content(fn () => ProjectCharter::getStatuses()[$record->status] ?? $record->status),

                        Forms\Components\Placeholder::make('name')
                            ->label(__('project_charter.name'))
                            ->content(fn () => $record->name),

                        Forms\Components\Placeholder::make('project_manner')
                            ->label(__('project_charter.project_manner'))
                            ->content(fn () => $this->getProjectMannerDisplay($record)),
                    ]),

                Forms\Components\Placeholder::make('description')
                    ->label(__('project_charter.description'))
                    ->content(fn () => $record->description ?: __('project_charter.no_description'))
                    ->columnSpanFull(),
            ]);
    }

    /**
     * Get the timeline and financial information section
     */
    protected function getTimelineAndFinancialSection(ProjectCharter $record): Forms\Components\Grid
    {
        return Forms\Components\Grid::make(2)
            ->schema([
                $this->getTimelineSection($record),
                $this->getFinancialSection($record),
            ]);
    }

    /**
     * Get the progress and performance section with all tracking metrics
     */
    protected function getProgressAndPerformanceSection(ProjectCharter $record): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter.progress_and_performance'))
            ->icon('heroicon-o-chart-bar')
            ->schema([
                Forms\Components\Grid::make(3)
                    ->schema([
                        Forms\Components\Placeholder::make('total_expenses')
                            ->label(__('project_charter.total_expenses'))
                            ->content(function () use ($record) {
                                // Get total approved exchange requests value
                                $totalExpenses = $record->total_approved_exchange_requests ?? 0;

                                return number_format($totalExpenses, 2).' SAR';
                            }),

                        Forms\Components\Placeholder::make('project_progress_percentage')
                            ->label(__('project_charter.project_progress_percentage'))
                            ->content(fn () => number_format($record->project_progress ?? 0, 1).'%'),

                        Forms\Components\Placeholder::make('financial_progress_percentage')
                            ->label(__('project_charter.financial_progress_percentage'))
                            ->content(fn () => number_format($record->financial_progress ?? 0, 1).'%'),

                        Forms\Components\Placeholder::make('deviation_percentage')
                            ->label(__('project_charter.deviation_percentage'))
                            ->content(function () use ($record) {
                                // Calculate deviation based on expected vs actual progress
                                $expectedProgress = $this->calculateExpectedProgress($record);
                                $actualProgress = $record->project_progress ?? 0;
                                $deviation = $actualProgress - $expectedProgress;
                                $color = $deviation >= 0 ? 'text-green-600' : 'text-red-600';
                                $sign = $deviation >= 0 ? '+' : '';

                                return new HtmlString("<span class=\"{$color} font-semibold\">{$sign}".number_format($deviation, 1).'%</span>');
                            }),
                    ]),

                // Add deliverables section
                $this->getDeliverablesSection($record),
            ]);
    }

    /**
     * Get the timeline section
     */
    protected function getTimelineSection(ProjectCharter $record): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter.timeline'))
            ->icon('heroicon-o-calendar-days')
            ->schema([
                Forms\Components\Placeholder::make('start_date')
                    ->label(__('project_charter.start_date'))
                    ->content(fn () => $record->start_date ? $record->start_date : '-'),

                Forms\Components\Placeholder::make('expected_end_date')
                    ->label(__('project_charter.expected_end_date'))
                    ->content(fn () => $record->expected_end_date ? $record->expected_end_date : '-'),
            ])
            ->columns(2);
    }

    /**
     * Get the deliverables section showing deliverables information
     */
    protected function getDeliverablesSection(ProjectCharter $record): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter_deliverable.deliverables'))
            ->icon('heroicon-o-document-duplicate')
            ->schema([
                Forms\Components\Placeholder::make('deliverables_list')
                    ->label('')
                    ->content(function () use ($record) {
                        $deliverables = $record->deliverables;

                        if ($deliverables->isEmpty()) {
                            return new HtmlString('<div class="text-gray-500 text-center py-4">'.__('project_charter_deliverable.no_deliverables').'</div>');
                        }

                        $html = '<div class="space-y-4">';

                        foreach ($deliverables as $deliverable) {
                            $fileStatusColor = match ($deliverable->file_status) {
                                'pending' => 'bg-yellow-100 text-yellow-800',
                                'approved' => 'bg-green-100 text-green-800',
                                'rejected' => 'bg-red-100 text-red-800',
                                default => 'bg-gray-100 text-gray-800',
                            };

                            $fileStatusText = $deliverable->file_status ?
                                __('project_charter_deliverable.file_status_'.$deliverable->file_status) :
                                __('project_charter_deliverable.no_file');

                            $hasFileIcon = $deliverable->hasFile() ?
                                '<span class="text-green-600">✓</span>' :
                                '<span class="text-gray-400">○</span>';

                            // Get progress percentage if method exists
                            $progressPercentage = method_exists($deliverable, 'getProgressPercentageAttribute') ?
                                $deliverable->progress_percentage : null;

                            $html .= '
                            <div class="border border-gray-200 rounded-lg p-4 bg-white">
                                <div class="flex justify-between items-start mb-3">
                                    <h4 class="font-semibold text-gray-900">'.e($deliverable->name).'</h4>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium '.$fileStatusColor.'">
                                        '.$fileStatusText.'
                                    </span>
                                </div>';

                            // Add progress bar if progress percentage is available
                            if ($progressPercentage !== null) {
                                $progressColor = $progressPercentage == 100 ? 'bg-green-500' : 'bg-blue-500';
                                $html .= '
                                <div class="mb-3">
                                    <div class="flex justify-between text-sm text-gray-600 mb-1">
                                        <span>التقدم</span>
                                        <span>'.number_format($progressPercentage, 1).'%</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="'.$progressColor.' h-2 rounded-full" style="width: '.$progressPercentage.'%"></div>
                                    </div>
                                </div>';
                            }

                            $html .= '
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                                    <div>
                                        <span class="text-gray-500">'.__('project_charter_deliverable.expected_delivery_date').':</span>
                                        <div class="font-medium">'.($deliverable->expected_delivery_date ? $deliverable->expected_delivery_date->format('d M Y') : '-').'</div>
                                    </div>
                                    
                                    <div>
                                        <span class="text-gray-500">'.__('project_charter_deliverable.estimated_cost').':</span>
                                        <div class="font-medium flex items-center">
                                            <span class="icon-saudi_riyal mr-1 text-xs"></span>
                                            '.number_format($deliverable->estimated_cost ?? 0, 2).'
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <span class="text-gray-500">'.__('project_charter_deliverable.has_file').':</span>
                                        <div class="font-medium flex items-center">
                                            '.$hasFileIcon.'
                                            <span class="ml-1">'.($deliverable->hasFile() ? 'نعم' : 'لا').'</span>
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <span class="text-gray-500">'.__('project_charter_deliverable.created_at').':</span>
                                        <div class="font-medium">'.$deliverable->created_at->format('d M Y').'</div>
                                    </div>
                                </div>
                            </div>';
                        }

                        $html .= '</div>';

                        return new HtmlString($html);
                    })
                    ->columnSpanFull(),
            ])
            ->collapsible()
            ->collapsed(false);
    }

    /**
     * Get the financial section
     */
    protected function getFinancialSection(ProjectCharter $record): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter.financial_information'))
            ->icon('heroicon-o-banknotes')
            ->schema([
                Forms\Components\Placeholder::make('estimated_cost')
                    ->label(__('project_charter.estimated_cost'))
                    ->content(fn () => number_format($record->estimated_cost ?? 0, 2).' SAR'),

                Forms\Components\Placeholder::make('total_cost')
                    ->label(__('project_charter.total_cost'))
                    ->content(fn () => number_format($record->total_cost ?? 0, 2).' SAR'),
            ])
            ->columns(2);
    }

    /**
     * Get the closure details input section
     */
    protected function getClosureDetailsSection(): Forms\Components\Section
    {
        return Forms\Components\Section::make(__('project_charter.closure_details'))
            ->icon('heroicon-o-document-check')
            ->schema([
                Forms\Components\DatePicker::make('actual_end_date')
                    ->label(__('project_charter.actual_end_date'))
                    ->required()
                    ->default(now())
                    ->maxDate(now())
                    ->helperText(__('project_charter.actual_end_date_helper')),

                Forms\Components\Textarea::make('learned_lessons')
                    ->label(__('project_charter.learned_lessons'))
                    ->required()
                    ->rows(4)
                    ->placeholder(__('project_charter.learned_lessons_placeholder'))
                    ->helperText(__('project_charter.learned_lessons_helper')),

                Forms\Components\Textarea::make('notes')
                    ->label(__('project_charter.closure_notes'))
                    ->required()
                    ->rows(3)
                    ->placeholder(__('project_charter.closure_notes_placeholder'))
                    ->helperText(__('project_charter.closure_notes_helper')),

                Forms\Components\SpatieMediaLibraryFileUpload::make('closure_attachments')
                    ->label(__('project_charter.closure_attachments'))
                    ->multiple()
                    ->collection('closure_attachments')
                    ->visibility('private')
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240) // 10MB
                    ->helperText(__('project_charter.closure_attachments_helper'))
                    ->columnSpanFull(),
            ]);
    }

    /**
     * Get formatted display for project manner
     */
    protected function getProjectMannerDisplay(ProjectCharter $record): string
    {
        $projectManner = $record->initiativeProject?->initiative?->performanceCard?->project_manner;

        if (! $projectManner) {
            return '-';
        }

        $projectManners = \App\Models\PerformanceCard::getProjectManners();

        return $projectManners[$projectManner] ?? $projectManner;
    }

    /**
     * Calculate expected progress based on timeline
     */
    protected function calculateExpectedProgress(ProjectCharter $record): float
    {
        if (! $record->start_date || ! $record->expected_end_date) {
            return 0;
        }

        $startDate = \Carbon\Carbon::parse($record->start_date);
        $endDate = \Carbon\Carbon::parse($record->expected_end_date);
        $currentDate = \Carbon\Carbon::now();

        if ($currentDate <= $startDate) {
            return 0;
        }

        if ($currentDate >= $endDate) {
            return 100;
        }

        $totalDays = $startDate->diffInDays($endDate);
        $elapsedDays = $startDate->diffInDays($currentDate);

        return ($elapsedDays / $totalDays) * 100;
    }
}
