<?php

namespace App\Filament\Admin\Resources\Orders\Forms;

use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Flex;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Enums\TextSize;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;
use RalphJSmit\Filament\Activitylog\Filament\Infolists\Components\Timeline;
use Spatie\Activitylog\Models\Activity;

class OrderInfolist
{
    public static function make(Schema $schema): Schema
    {
        return $schema
            ->components([
                Flex::make([
                    // Left Column - Main Project Information
                    Grid::make(1)
                        ->schema([
                            // Current Status Card
                            Section::make(__('order.current_status'))
                                ->icon('heroicon-o-check-circle')
                                ->schema([
                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('workflow_status')
                                                ->label(__('order.workflow_status'))
                                                ->getStateUsing(function ($record) {
                                                    return $record->getWorkflowStatusLabel();
                                                })
                                                ->badge()
                                                ->color(function ($record) {
                                                    if (! $record->hasWorkflow()) {
                                                        return 'gray';
                                                    }

                                                    $currentStep = $record->currentStep();
                                                    if (! $currentStep) {
                                                        return 'success'; // Completed
                                                    }

                                                    return match ($currentStep->status) {
                                                        'pending' => 'warning',
                                                        'approved' => 'success',
                                                        'rejected' => 'danger',
                                                        default => 'gray',
                                                    };
                                                })
                                                ->icon(function ($record) {
                                                    if (! $record->hasWorkflow()) {
                                                        return 'heroicon-o-minus-circle';
                                                    }

                                                    $currentStep = $record->currentStep();
                                                    if (! $currentStep) {
                                                        return 'heroicon-o-check-circle'; // Completed
                                                    }

                                                    return match ($currentStep->status) {
                                                        'pending' => 'heroicon-o-clock',
                                                        'approved' => 'heroicon-o-check-circle',
                                                        'rejected' => 'heroicon-o-x-circle',
                                                        default => 'heroicon-o-question-mark-circle',
                                                    };
                                                }),

                                            TextEntry::make('current_step')
                                                ->label(__('order.current_step'))
                                                ->getStateUsing(function ($record) {
                                                    if (! $record->hasWorkflow()) {
                                                        return __('order.no_workflow');
                                                    }

                                                    $currentStep = $record->currentStep();
                                                    if (! $currentStep) {
                                                        return __('order.workflow_completed');
                                                    }

                                                    return $currentStep->getLabel();
                                                })
                                                ->icon('heroicon-o-arrow-right')
                                                ->color('primary'),
                                        ]),
                                ]),

                            // Project Information Card
                            Section::make(__('order.project_information'))
                                ->icon('heroicon-o-clipboard-document-list')
                                ->schema([
                                    Grid::make(1)
                                        ->schema([
                                            TextEntry::make('name')
                                                ->label(__('order.project_name'))
                                                ->weight(FontWeight::Bold)
                                                ->size(TextSize::Large)
                                                ->color('primary')
                                                ->icon('heroicon-o-rocket-launch'),

                                            TextEntry::make('idea')
                                                ->label(__('order.project_idea'))
                                                ->prose()
                                                ->markdown()
                                                ->columnSpanFull(),
                                        ]),

                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('grantArea.name')
                                                ->label(__('order.grant_area'))
                                                ->badge()
                                                ->color('success')
                                                ->icon('heroicon-o-academic-cap'),

                                            TextEntry::make('association.name')
                                                ->label(__('order.association'))
                                                ->color('gray')
                                                ->icon('heroicon-o-building-library'),

                                            TextEntry::make('target_group_type')
                                                ->label(__('order.target_group_type'))
                                                ->icon('heroicon-o-user-group'),

                                            TextEntry::make('beneficiaries_count')
                                                ->label(__('order.beneficiaries_count'))
                                                ->icon('heroicon-o-users')
                                                ->formatStateUsing(fn ($state) => number_format($state).' '.__('order.beneficiaries')),
                                        ]),
                                ]),

                            // Timeline and Location Card
                            Section::make(__('order.timeline_and_scope'))
                                ->icon('heroicon-o-calendar-days')
                                ->schema([
                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('start_date')
                                                ->label(__('order.start_date'))
                                                ->date()
                                                ->icon('heroicon-o-calendar')
                                                ->color('success'),

                                            TextEntry::make('end_date')
                                                ->label(__('order.end_date'))
                                                ->date()
                                                ->icon('heroicon-o-flag')
                                                ->color('warning'),

                                            TextEntry::make('duration_months')
                                                ->label(__('order.duration'))
                                                ->icon('heroicon-o-clock')
                                                ->formatStateUsing(fn ($state) => $state.' '.__('order.months'))
                                                ->badge()
                                                ->color('gray'),

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

                            // Location Details Card
                            Section::make(__('order.location'))
                                ->icon('heroicon-o-map-pin')
                                ->schema([
                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('state.name')
                                                ->label(__('order.state'))
                                                ->badge()
                                                ->color('gray')
                                                ->icon('heroicon-o-map'),

                                            TextEntry::make('city.name')
                                                ->label(__('order.city'))
                                                ->badge()
                                                ->color('gray')
                                                ->icon('heroicon-o-building-office-2'),

                                            TextEntry::make('lat')
                                                ->label(__('order.latitude'))
                                                ->icon('heroicon-o-globe-alt')
                                                ->copyable(),

                                            TextEntry::make('lng')
                                                ->label(__('order.longitude'))
                                                ->icon('heroicon-o-globe-alt')
                                                ->copyable(),
                                        ]),

                                    TextEntry::make('location')
                                        ->label(__('order.location'))
                                        ->formatStateUsing(function ($state) {
                                            if (! $state || ! is_array($state) || ! isset($state['lat'], $state['lng'])) {
                                                return '—';
                                            }

                                            return "Lat: {$state['lat']}, Lng: {$state['lng']}";
                                        })
                                        ->icon('heroicon-o-map-pin')
                                        ->color('primary')
                                        ->columnSpanFull(),
                                ]),

                            // Project Analysis Card
                            Section::make(__('order.project_analysis'))
                                ->icon('heroicon-o-chart-bar-square')
                                ->schema([
                                    TextEntry::make('goals')
                                        ->label(__('order.goals'))
                                        ->prose()
                                        ->markdown()
                                        ->columnSpanFull(),

                                    TextEntry::make('strengths')
                                        ->label(__('order.strengths'))
                                        ->prose()
                                        ->markdown()
                                        ->columnSpanFull(),

                                    TextEntry::make('risks')
                                        ->label(__('order.risks'))
                                        ->prose()
                                        ->markdown()
                                        ->columnSpanFull(),
                                ]),
                        ]),

                    // Right Column - Additional Information
                    Grid::make(1)
                        ->schema([
                            // Project Deliverables Card
                            Section::make(__('order.project_deliverables'))
                                ->icon('heroicon-o-clipboard-document')
                                ->schema([
                                    TextEntry::make('deliverables_count')
                                        ->label(__('order.deliverables_count'))
                                        ->formatStateUsing(fn ($record) => $record->deliverables()->count())
                                        ->badge()
                                        ->color('info')
                                        ->icon('heroicon-o-list-bullet'),

                                    TextEntry::make('deliverables.name')
                                        ->label(__('order.deliverables'))
                                        ->listWithLineBreaks()
                                        ->bulleted()
                                        ->prose()
                                        ->columnSpanFull(),
                                ]),

                            // Finance Information Card
                            Section::make(__('order.finance_information'))
                                ->icon('heroicon-o-currency-dollar')
                                ->schema([
                                    TextEntry::make('finance_status')
                                        ->label(__('order.finance_information'))
                                        ->getStateUsing(function ($record) {
                                            return $record->finance ? 'Available' : __('order.no_finance_info');
                                        })
                                        ->badge()
                                        ->color(fn ($record) => $record->finance ? 'success' : 'gray')
                                        ->icon(fn ($record) => $record->finance ? 'heroicon-o-check-circle' : 'heroicon-o-minus-circle')
                                        ->columnSpanFull()
                                        ->visible(fn ($record) => ! $record->finance),

                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('finance.company_name')
                                                ->label(__('order.company_name'))
                                                ->icon('heroicon-o-building-office')
                                                ->color('primary'),

                                            TextEntry::make('finance.execution_duration')
                                                ->label(__('order.execution_duration'))
                                                ->formatStateUsing(fn ($state) => $state ? $state.' '.__('order.execution_duration_days') : '—')
                                                ->icon('heroicon-o-clock')
                                                ->badge()
                                                ->color('info'),

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

                                            TextEntry::make('finance.created_at')
                                                ->label(__('common.created_at'))
                                                ->dateTime()
                                                ->icon('heroicon-o-calendar')
                                                ->color('gray'),
                                        ])
                                        ->visible(fn ($record) => $record->finance),
                                ]),

                            // Agreement Information Card
                            Section::make(__('order.agreement_information'))
                                ->icon('heroicon-o-document-text')
                                ->schema([
                                    TextEntry::make('agreement_status')
                                        ->label(__('order.agreement_information'))
                                        ->getStateUsing(function ($record) {
                                            return $record->agreement ? 'Available' : __('order.no_agreement_info');
                                        })
                                        ->badge()
                                        ->color(fn ($record) => $record->agreement ? 'success' : 'gray')
                                        ->icon(fn ($record) => $record->agreement ? 'heroicon-o-check-circle' : 'heroicon-o-minus-circle')
                                        ->columnSpanFull()
                                        ->visible(fn ($record) => ! $record->agreement),

                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('agreement.contract_number')
                                                ->label(__('order.contract_number'))
                                                ->icon('heroicon-o-hashtag')
                                                ->color('primary')
                                                ->copyable(),

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

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

                                            TextEntry::make('agreement.created_at')
                                                ->label(__('common.created_at'))
                                                ->dateTime()
                                                ->icon('heroicon-o-calendar')
                                                ->color('gray'),
                                        ])
                                        ->visible(fn ($record) => $record->agreement),
                                ]),

                            // Project Team Card
                            Section::make(__('association.contact_information'))
                                ->icon('heroicon-o-users')
                                ->schema([
                                    TextEntry::make('createdBy.name')
                                        ->label(__('common.created_by'))
                                        ->icon('heroicon-o-user')
                                        ->color('gray'),

                                    TextEntry::make('association.representative.name')
                                        ->label(__('association.representative'))
                                        ->icon('heroicon-o-identification')
                                        ->color('gray'),

                                    TextEntry::make('association.representative.email')
                                        ->label(__('common.email'))
                                        ->icon('heroicon-o-envelope')
                                        ->copyable(),

                                    TextEntry::make('association.representative.phone')
                                        ->label(__('common.phone'))
                                        ->icon('heroicon-o-phone')
                                        ->copyable(),
                                ]),

                            // Attachments Card
                            Section::make(__('order.attachments'))
                                ->icon('heroicon-o-paper-clip')
                                ->schema([
                                    TextEntry::make('support_letter')
                                        ->label(__('order.support_letter'))
                                        ->formatStateUsing(function ($record) {
                                            $media = $record->getFirstMedia('support_letter');

                                            return $media
                                                ? new HtmlString('<a class="text-blue-500 hover:underline" href="'.$media->getUrl().'" target="_blank">Download Support Letter</a>')
                                                : 'No support letter uploaded';
                                        })
                                        ->icon('heroicon-o-document')
                                        ->color(fn ($record) => $record->getFirstMedia('support_letter') ? 'success' : 'gray'),

                                    TextEntry::make('project_attachments')
                                        ->label(__('order.project_attachments'))
                                        ->formatStateUsing(function ($record) {
                                            $attachments = $record->getMedia('project_attachments');
                                            if ($attachments->isEmpty()) {
                                                return 'No project attachments';
                                            }

                                            return $attachments->map(function ($media) {
                                                return new HtmlString('<a class="text-blue-500 hover:underline block" href="'.$media->getUrl().'" target="_blank">'.$media->name.'</a>');
                                            })->join('');
                                        })
                                        ->icon('heroicon-o-folder')
                                        ->columnSpanFull(),
                                ]),

                            // Metadata Card
                            Section::make(__('common.metadata'))
                                ->icon('heroicon-o-information-circle')
                                ->schema([
                                    Grid::make(2)
                                        ->schema([
                                            TextEntry::make('created_at')
                                                ->label(__('common.created_at'))
                                                ->dateTime()
                                                ->icon('heroicon-o-calendar'),

                                            TextEntry::make('updated_at')
                                                ->label(__('common.updated_at'))
                                                ->dateTime()
                                                ->icon('heroicon-o-calendar'),
                                        ]),
                                ]),
                        ]),
                ])->from('md')
                    ->columnSpanFull(),

                // Activity Timeline - Full Width Section
                Section::make(__('workflow.general.actions'))
                    ->icon('heroicon-o-clock')
                    ->schema([
                        Timeline::make('activities')
                            ->modifyActivitiesQueryUsing(function (Builder $query) {
                                return $query->whereIn('event', ['workflow_step_approved', 'workflow_step_rejected', 'workflow_completed']);
                            })
                            ->itemIcons([
                                'workflow_step_approved' => 'heroicon-o-check-circle',
                                'workflow_step_rejected' => 'heroicon-o-x-circle',
                                'workflow_completed' => 'heroicon-o-flag',
                            ])
                            ->itemIconColors([
                                'workflow_step_approved' => 'info',
                                'workflow_step_rejected' => 'danger',
                                'workflow_completed' => 'success',
                            ])
                            ->eventDescriptions([
                                'workflow_step_approved' => function (Activity $activity) {
                                    $from_step = $activity->getExtraProperty('from_step');
                                    $to_step = $activity->getExtraProperty('to_step');

                                    $description = __('order.order_approved_by', ['name' => $activity->causer?->name]);
                                    if ($from_step && $to_step) {
                                        $description .= '<br/>'.__('order.status_changed', ['old_status' => $from_step, 'new_status' => $to_step]);
                                    }

                                    return new HtmlString($description);
                                },
                                'workflow_step_rejected' => function (Activity $activity) {
                                    $step = $activity->getExtraProperty('step');
                                    $description = __('order.order_rejected_by', ['name' => $activity->causer?->name]);
                                    if ($step) {
                                        $description .= ' '.__('order.status_was', ['status' => $step]);
                                    }

                                    return new HtmlString($description);
                                },
                                'workflow_completed' => function (Activity $activity) {
                                    $description = __('order.workflow_completed_by', ['name' => $activity->causer?->name]);

                                    return new HtmlString($description);
                                },
                            ])
                            ->itemBadges([
                                'workflow_step_approved' => function (Activity $activity) {
                                    $notes = $activity->getExtraProperty('notes');

                                    return $notes ? __('order.workflow_notes', ['notes' => $notes]) : __('order.notes_na');
                                },
                                'workflow_step_rejected' => function (Activity $activity) {
                                    $notes = $activity->getExtraProperty('notes');

                                    return $notes ? __('order.workflow_notes', ['notes' => $notes]) : __('order.notes_na');
                                },
                                'workflow_completed' => function (Activity $activity) {
                                    $notes = $activity->getExtraProperty('notes');

                                    return $notes ? __('order.workflow_notes', ['notes' => $notes]) : __('order.notes_na');
                                },
                            ])
                            ->itemBadgeColors([
                                'workflow_step_approved' => 'info',
                                'workflow_step_rejected' => 'danger',
                                'workflow_completed' => 'success',
                            ]),
                    ])
                    ->collapsible()
                    ->columnSpanFull(),
            ]);
    }
}
