<?php

namespace App\Filament\Resources\OrderResource\Pages;

use App\Filament\Resources\AssociationResource;
use App\Filament\Resources\OrderResource;
use App\Filament\Resources\OrderResource\Components\OrderApprovalFlow;
use App\Models\Order;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Forms\Get;
use Filament\Infolists\Components\Actions\Action;
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\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;
use RalphJSmit\Filament\Activitylog\Actions\TimelineAction;
use RalphJSmit\Filament\Activitylog\Infolists\Components\Timeline;
use Spatie\Activitylog\Models\Activity;

class ViewOrder extends ViewRecord
{
    protected static string $resource = OrderResource::class;

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

        if ($record->status !== Order::STATUS_REJECTED) {
            $actions[] = Actions\EditAction::make();
        }

        // Add approval actions if user has permission
        if ($record->canApproveToNextStage()) {
            array_push($actions, ...OrderApprovalFlow::getApprovalFlowActions($record));
        }

        $actions[] = TimelineAction::make()
            ->label(__('order.timeline'))
            ->modifyTimelineUsing(function (Timeline $timeline) {
                return $timeline
                    ->modifyActivitiesQueryUsing(function (Builder $query) {
                        return $query->whereIn('event', ['approved', 'rejected', 'send_back']);
                    })
                    ->itemIcon('approved', 'heroicon-o-check-circle')
                    ->itemIconColor('approved', 'success')
                    ->itemIcon('rejected', 'heroicon-o-x-circle')
                    ->itemIconColor('rejected', 'danger')
                    ->eventDescriptions([
                        'approved' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = Order::getOrderStatuses()[$oldStatus] ?? $oldStatus;
                            $newStatusName = Order::getOrderStatuses()[$newStatus] ?? $newStatus;

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

                            return new HtmlString($description);
                        },
                        'rejected' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $oldStatusName = Order::getOrderStatuses()[$oldStatus] ?? $oldStatus;
                            $description = __('order.order_rejected_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus) {
                                $description .= ' '.__('order.status_was', ['status' => $oldStatusName]);
                            }

                            return new HtmlString($description);
                        },
                        'send_back' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = Order::getOrderStatuses()[$oldStatus] ?? $oldStatus;
                            $newStatusName = Order::getOrderStatuses()[$newStatus] ?? $newStatus;

                            $description = __('order.order_sent_back_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus && $newStatus) {
                                $description .= '<br/>'.__('order.status_changed', ['old_status' => $oldStatusName, 'new_status' => $newStatusName]);
                            }

                            return new HtmlString($description);
                        },
                    ])
                    ->itemBadge(
                        'approved',
                        fn (Activity $activity) => $activity->getExtraProperty('notes')
                            ? __('order.notes', ['notes' => $activity->getExtraProperty('notes')])
                            : __('order.notes_na'),
                        [Order::class]
                    )
                    ->itemBadgeColor('approved', 'success')
                    ->itemBadge(
                        'rejected',
                        fn (Activity $activity) => $activity->getExtraProperty('notes')
                            ? __('order.notes', ['notes' => $activity->getExtraProperty('notes')])
                            : __('order.notes_na'),
                        [Order::class]
                    )
                    ->itemBadgeColor('rejected', 'danger')
                    ->emptyStateHeading(__('order.no_timeline_activities'))
                    ->emptyStateDescription(__('order.no_timeline_activities_description'));
            });

        return $actions;
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Grid::make(1)
                    ->schema([
                        // Order Status Bar
                        $this->getOrderStatusesBar(),
                        // Order Info Split
                        $this->getOrderInfoSplit(),
                    ]),
            ]);
    }

    public function getOrderStatusesBar(): ViewEntry
    {
        return ViewEntry::make('order_status_bar')
            ->view('filament.components.order-status-bar')
            ->columnSpanFull();
    }

    public function getOrderInfoSplit(): Split
    {
        return Split::make([
            // First Column
            Grid::make(1)
                ->schema([
                    // Order Details Card
                    Section::make(__('order.order_details'))
                        ->icon('heroicon-o-document-text')
                        ->schema([

                            TextEntry::make('status')
                                // hide label
                                ->label('')
                                ->formatStateUsing(
                                    fn (string $state): string => __(Order::getOrderStatuses()[$state] ?? $state)
                                )
                                ->badge()
                                ->color(fn (string $state): string => match ($state) {
                                    Order::STATUS_CREATED => 'gray',
                                    Order::STATUS_PENDING_RECOMMENDATION => 'warning',
                                    Order::STATUS_RECOMMENDED => 'info',
                                    Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED => 'warning',
                                    Order::STATUS_TECHNICAL_FINANCIAL_APPROVED => 'success',
                                    Order::STATUS_PROJECT_MANAGER_APPROVED => 'success',
                                    Order::STATUS_CLASSIFICATION => 'info',
                                    Order::STATUS_AGREEMENT => 'info',
                                    Order::STATUS_CEO_APPROVED => 'success',
                                    Order::STATUS_LAUNCHED => 'gray',
                                    Order::STATUS_ACCEPTED => 'success',
                                    Order::STATUS_REJECTED => 'danger',
                                    default => 'gray',
                                }),

                            // reason from getCurrentStatusNotes if it exist
                            TextEntry::make('current_status_notes')
                                ->label(__('order.current_status_notes'))
                                ->visible(fn (Order $record): bool => ! empty($record->current_status_notes)),

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

                            ViewEntry::make('separator')
                                ->view('filament.components.separator')
                                ->columnSpanFull(),

                            TextEntry::make('developmentImpacts.name')
                                ->label(__('order.development_impacts'))
                                ->listWithLineBreaks()
                                ->bulleted()
                                ->columnSpanFull(),

                            ViewEntry::make('separator')
                                ->view('filament.components.separator')
                                ->columnSpanFull(),

                            Grid::make(3)
                                ->schema([
                                    TextEntry::make('id')
                                        ->label(__('order.order_number'))
                                        ->weight(FontWeight::SemiBold)
                                        ->color('gray')
                                        ->badge()
                                        ->prefix('#'),

                                    TextEntry::make('type')
                                        ->label(__('order.order_type'))
                                        ->formatStateUsing(
                                            fn (string $state): string => __(Order::getOrderTypes()[$state] ?? $state)
                                        )
                                        ->badge()
                                        ->color('gray'),

                                    TextEntry::make('calculated_families_count')
                                        ->label(__('order.families_count_from_centers'))
                                        ->icon('heroicon-o-calculator')
                                        ->numeric()
                                        ->state(function (Order $record): int {
                                            return $record->calculateTotalFamilies();
                                        })
                                        ->badge()
                                        ->color('success')
                                        ->helperText(__('order.used_in_reports')),

                                    TextEntry::make('number_of_families')
                                        ->label(__('order.manual_families_entry'))
                                        ->icon('heroicon-o-user-group')
                                        ->numeric()
                                        ->helperText(__('order.manual_entry_by_association')),

                                    TextEntry::make('state.name')
                                        ->label(__('order.state'))
                                        ->icon('heroicon-o-map-pin'),

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

                                    TextEntry::make('centers.name')
                                        ->label(__('order.centers'))
                                        ->badge()
                                        ->color('gray')
                                        ->separator(' '),

                                    TextEntry::make('residentialGatherings.name')
                                        ->label(__('order.residential_gatherings'))
                                        ->badge()
                                        ->color('info')
                                        ->separator(' ')
                                        ->visible(fn (Order $record): bool => $record->residentialGatherings()->exists()),

                                ]),

                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('location')
                                        ->label(__('order.coordinates'))
                                        ->icon('heroicon-o-globe-alt')
                                        ->columnSpanFull()
                                        ->color('primary'),

                                    TextEntry::make('water_source')
                                        ->label(__('order.water_source'))
                                        ->formatStateUsing(function ($state): string {
                                            if (! $state) {
                                                return '';
                                            }

                                            // Handle both string (old enum) and array (new JSON) formats
                                            if (is_string($state)) {
                                                // If it's a JSON string, decode it
                                                $decoded = json_decode($state, true);
                                                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                                    $state = $decoded;
                                                } else {
                                                    // It's a single enum value, convert to array
                                                    $state = [$state];
                                                }
                                            }

                                            if (is_array($state)) {
                                                return collect($state)->map(fn ($source) => __(Order::getWaterSources()[$source] ?? $source))->join(', ');
                                            }

                                            return '';
                                        })
                                        ->badge()
                                        ->color('gray'),

                                    TextEntry::make('water_distance')
                                        ->label(__('order.water_distance'))
                                        ->suffix(' '.__('order.km_suffix'))
                                        ->icon('heroicon-o-map')
                                        ->numeric(2),
                                ]),

                            // TextEntry::make('order_justifications')
                            //     ->label(__('order.order_justifications'))
                            //     ->html()
                            //     ->columnSpanFull(),

                            TextEntry::make('rejection_notes')
                                ->label(__('order.rejection_notes'))
                                ->html()
                                ->columnSpanFull()
                                ->color('danger')
                                ->visible(fn ($record) => $record->status === Order::STATUS_REJECTED && ! empty($record->rejection_notes)),

                        ]),

                    // Order Agreement Card
                    Section::make(__('order.agreement_information'))
                        ->icon('heroicon-o-document-text')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('agreement.contract_number')
                                        ->label(__('order_agreement.contract_number'))
                                        ->weight(FontWeight::SemiBold)
                                        ->icon('heroicon-o-document')
                                        ->badge()
                                        ->color('primary'),

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

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

                                    TextEntry::make('agreement.end_date')
                                        ->label(__('order_agreement.end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar')
                                        ->color('warning'),

                                    TextEntry::make('agreement.execution_duration')
                                        ->label(__('order_agreement.execution_duration'))
                                        ->suffix(' '.__('order_agreement.days'))
                                        ->icon('heroicon-o-clock')
                                        ->numeric(),

                                    TextEntry::make('order_agreement.agreement_file')
                                        ->label(__('order_agreement.agreement_file'))
                                        ->icon('heroicon-o-paper-clip')
                                        ->color('primary')
                                        ->state(fn (Order $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->getAgreementFileUrl().'" target="_blank">'.
                                            __('order_agreement.download_agreement_file').'</a>')),
                                ]),
                        ])
                        ->visible(fn ($record) => $record->agreement !== null),

                ]),

            // Second Column
            Grid::make(1)
                ->schema([
                    // Association Info Card
                    Section::make(__('order.association_information'))
                        ->icon('heroicon-o-building-office-2')
                        ->schema([
                            TextEntry::make('association.name')
                                ->label(__('order.association_name'))
                                ->weight(FontWeight::SemiBold)
                                ->icon('heroicon-o-building-office-2')
                                ->url(fn ($record) => $record->association ? AssociationResource::getUrl('view', ['record' => $record->association]) : null)
                                ->color('primary')
                                ->openUrlInNewTab(false),

                            Grid::make(2)
                                ->schema([

                                    TextEntry::make('association.representative_full_name')
                                        ->label(__('association.representative'))
                                        ->icon('heroicon-o-user')
                                        ->copyable(),

                                    TextEntry::make('association.phone_number')
                                        ->label(__('order.association_phone'))
                                        ->icon('heroicon-o-phone')
                                        ->copyable(),
                                ]),
                        ]),

                    // values references already defined in the system
                    Section::make(__('order.pre_registered_information'))
                        ->icon('heroicon-o-information-circle')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('actual_families_count')
                                        ->label(__('order.actual_families_count'))
                                        ->state(function ($record) {
                                            $centerIds = $record->residentialGatherings->pluck('id')->toArray();
                                            if (empty($centerIds)) {
                                                return new HtmlString('<span class="text-gray-500">—</span>');
                                            }

                                            $totalFamilies = \App\Models\ResidentialGathering::whereIn('id', $centerIds)->sum('families_count');

                                            return new HtmlString(
                                                '<span class="inline-flex items-center gap-2">
                                            <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                                                      d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM9 3a2 2 0 11-4 0 2 2 0 014 0z" />
                                            </svg>
                                            <span class="font-semibold text-blue-600">'.number_format($totalFamilies).'</span>
                                            <span class="text-gray-600">'.__('order.families').'</span>
                                        </span>'
                                            );
                                        })
                                        ->html(),

                                    \Filament\Infolists\Components\Actions::make([
                                        Action::make('view_location_map')
                                            ->label(__('order.location_map'))
                                            ->icon('heroicon-o-map')
                                            ->color('primary')
                                            ->modalHeading(__('order.location_map'))
                                            ->modalWidth('7xl')
                                            ->modalSubmitAction(false)
                                            ->modalCancelActionLabel(__('filament-actions::modal.actions.cancel.label'))
                                            ->form([
                                                \Cheesegrits\FilamentGoogleMaps\Fields\Map::make('location')
                                                    ->label(__('order.location'))
                                                    ->mapControls([
                                                        'mapTypeControl' => true,
                                                        'scaleControl' => true,
                                                        'streetViewControl' => true,
                                                        'rotateControl' => true,
                                                        'fullscreenControl' => true,
                                                        'searchBoxControl' => false,
                                                        'zoomControl' => true,
                                                    ])
                                                    ->height('500px')
                                                    ->defaultZoom(function ($record) {
                                                        // Calculate appropriate zoom level based on marker spread
                                                        if (empty($record->location) || ! isset($record->location['lat'], $record->location['lng'])) {
                                                            return 12;
                                                        }

                                                        $orderLat = (float) $record->location['lat'];
                                                        $orderLng = (float) $record->location['lng'];

                                                        $waterSources = \App\Models\WaterSource::all();
                                                        if ($waterSources->isEmpty()) {
                                                            return 15; // Close zoom if no water sources
                                                        }

                                                        // Find the maximum distance to any of the nearest 10 water sources
                                                        $maxDistance = $waterSources->map(function ($source) use ($orderLat, $orderLng) {
                                                            $sourceLat = (float) $source->lat;
                                                            $sourceLng = (float) $source->lng;

                                                            $earthRadius = 6371; // km
                                                            $dLat = deg2rad($sourceLat - $orderLat);
                                                            $dLng = deg2rad($sourceLng - $orderLng);

                                                            $a = sin($dLat / 2) * sin($dLat / 2) +
                                                                cos(deg2rad($orderLat)) * cos(deg2rad($sourceLat)) *
                                                                sin($dLng / 2) * sin($dLng / 2);
                                                            $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

                                                            return $earthRadius * $c;
                                                        })->sortBy(function ($distance) {
                                                            return $distance;
                                                        })->take(10)->max();

                                                        // Convert distance to appropriate zoom level
                                                        if ($maxDistance <= 1) {
                                                            return 16;
                                                        }      // Very close - city level
                                                        if ($maxDistance <= 5) {
                                                            return 14;
                                                        }      // Close - town level
                                                        if ($maxDistance <= 10) {
                                                            return 13;
                                                        }     // Medium - district level
                                                        if ($maxDistance <= 25) {
                                                            return 12;
                                                        }     // Far - county level
                                                        if ($maxDistance <= 50) {
                                                            return 11;
                                                        }     // Very far - regional level

                                                        return 10;                             // Extremely far - state level
                                                    })
                                                    ->geoJson(function ($record) {
                                                        // Get order location coordinates
                                                        if (empty($record->location) || ! isset($record->location['lat'], $record->location['lng'])) {
                                                            return null;
                                                        }

                                                        $orderLat = (float) $record->location['lat'];
                                                        $orderLng = (float) $record->location['lng'];

                                                        // Get all water sources
                                                        $waterSources = \App\Models\WaterSource::all();

                                                        if ($waterSources->isEmpty()) {
                                                            return null;
                                                        }

                                                        // Calculate distance and get nearest 10 water sources
                                                        $waterSourcesWithDistance = $waterSources->map(function ($source) use ($orderLat, $orderLng) {
                                                            // Calculate distance using Haversine formula
                                                            $sourceLat = (float) $source->lat;
                                                            $sourceLng = (float) $source->lng;

                                                            $earthRadius = 6371; // km
                                                            $dLat = deg2rad($sourceLat - $orderLat);
                                                            $dLng = deg2rad($sourceLng - $orderLng);

                                                            $a = sin($dLat / 2) * sin($dLat / 2) +
                                                                cos(deg2rad($orderLat)) * cos(deg2rad($sourceLat)) *
                                                                sin($dLng / 2) * sin($dLng / 2);
                                                            $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
                                                            $distance = $earthRadius * $c;

                                                            $source->distance = $distance;

                                                            return $source;
                                                        })->sortBy('distance')->take(10);

                                                        $features = [];

                                                        // Add order location marker
                                                        $features[] = [
                                                            'type' => 'Feature',
                                                            'geometry' => [
                                                                'type' => 'Point',
                                                                'coordinates' => [$orderLng, $orderLat],
                                                            ],
                                                            'properties' => [
                                                                'name' => 'Order Location',
                                                                'description' => 'Project Location #'.$record->id,
                                                            ],
                                                        ];

                                                        // Add water source markers
                                                        foreach ($waterSourcesWithDistance as $index => $source) {

                                                            $features[] = [
                                                                'type' => 'Feature',
                                                                'geometry' => [
                                                                    'type' => 'Point',
                                                                    'coordinates' => [(float) $source->lng, (float) $source->lat],
                                                                ],
                                                                'properties' => [
                                                                    'name' => $source->name,
                                                                    'description' => 'Water Source - '.number_format($source->distance, 2).' km away',
                                                                ],
                                                            ];

                                                            // Add polyline connecting order location to water source
                                                            $features[] = [
                                                                'type' => 'Feature',
                                                                'geometry' => [
                                                                    'type' => 'LineString',
                                                                    'coordinates' => [
                                                                        [$orderLng, $orderLat],
                                                                        [(float) $source->lng, (float) $source->lat],
                                                                    ],
                                                                ],
                                                                'properties' => [
                                                                    'name' => 'Route to '.$source->name,
                                                                    'description' => 'Route to '.$source->name.' - '.number_format($source->distance, 2).' km',
                                                                ],
                                                            ];
                                                        }

                                                        return json_encode([
                                                            'type' => 'FeatureCollection',
                                                            'features' => $features,
                                                        ]);
                                                    })
                                                    ->disabled() // Make it read-only
                                                    ->columnSpanFull(),

                                                // Water Sources List
                                                \Filament\Forms\Components\Placeholder::make('water_sources_list')
                                                    ->label(__('order.nearest_water_sources'))
                                                    ->content(function ($record) {
                                                        if (empty($record->location) || ! isset($record->location['lat'], $record->location['lng'])) {
                                                            return new HtmlString('<span class="text-gray-500">No location data available</span>');
                                                        }

                                                        $orderLat = (float) $record->location['lat'];
                                                        $orderLng = (float) $record->location['lng'];

                                                        // Get all water sources
                                                        $waterSources = \App\Models\WaterSource::all();

                                                        if ($waterSources->isEmpty()) {
                                                            return new HtmlString('<span class="text-gray-500">No water sources found</span>');
                                                        }

                                                        // Calculate distance and get nearest 10 water sources
                                                        $waterSourcesWithDistance = $waterSources->map(function ($source) use ($orderLat, $orderLng) {
                                                            // Calculate distance using Haversine formula
                                                            $sourceLat = (float) $source->lat;
                                                            $sourceLng = (float) $source->lng;

                                                            $earthRadius = 6371; // km
                                                            $dLat = deg2rad($sourceLat - $orderLat);
                                                            $dLng = deg2rad($sourceLng - $orderLng);

                                                            $a = sin($dLat / 2) * sin($dLat / 2) +
                                                                cos(deg2rad($orderLat)) * cos(deg2rad($sourceLat)) *
                                                                sin($dLng / 2) * sin($dLng / 2);
                                                            $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
                                                            $distance = $earthRadius * $c;

                                                            $source->distance = $distance;

                                                            return $source;
                                                        })->sortBy('distance')->take(10);

                                                        $listItems = [];
                                                        $number = 1;
                                                        foreach ($waterSourcesWithDistance as $index => $source) {
                                                            $coordinates = number_format((float) $source->lat, 6).', '.number_format((float) $source->lng, 6);
                                                            $distance = number_format($source->distance, 1);

                                                            $listItems[] = '<div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                                        <span class="flex-shrink-0 w-8 h-8 bg-blue-500 text-white text-sm font-bold rounded-full flex items-center justify-center">'.$number++.'</span>
                                                        <div class="flex-1">
                                                            <div class="font-medium text-gray-900 mb-1">'.e($source->name).'</div>
                                                            <div class="text-sm text-gray-600 mb-1">الإحداثيات: '.$coordinates.'</div>
                                                            <div class="text-sm text-blue-600 font-medium">يبعد '.$distance.' كم عن إحداثيات المشروع</div>
                                                        </div>
                                                    </div>';
                                                        }

                                                        return new HtmlString('<div class="max-h-80 overflow-y-auto space-y-3 pr-2">'.implode('', $listItems).'</div>');
                                                    })
                                                    ->columnSpanFull(),
                                            ])
                                            ->fillForm(function ($record) {
                                                if ($record && $record->lat && $record->lng) {
                                                    return [
                                                        'location' => [
                                                            'lat' => (float) $record->lat,
                                                            'lng' => (float) $record->lng,
                                                        ],
                                                    ];
                                                }

                                                return ['location' => null];
                                            })
                                            ->visible(fn ($record) => ! empty($record->lat) && ! empty($record->lng)),
                                    ]),
                                ]),
                        ]),

                    // Uploaded Files Card
                    Section::make(__('order.uploaded_files'))
                        ->icon('heroicon-o-paper-clip')
                        ->schema([
                            TextEntry::make('media')
                                ->label(__('order.files'))
                                ->formatStateUsing(function ($record) {
                                    $media = $record->getOrderFiles();
                                    if ($media->isEmpty()) {
                                        return new HtmlString('<span class="text-gray-500">'.__('order.no_files_uploaded').'</span>');
                                    }

                                    $links = $media->map(function ($file) {
                                        return '<a href="'.$file?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" 
                                                          class="inline-flex items-center gap-1 text-primary-600 hover:text-primary-800 underline" 
                                                          target="_blank">
                                                          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                                                                    d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                                          </svg>
                                                          '.($file->getCustomProperty('file_title') ?? $file->name).'
                                                       </a>';
                                    })->implode('<br>');

                                    return new HtmlString($links);
                                })
                                ->html(),
                        ]),

                    // Order Finance Card
                    Section::make(__('order.financial_information'))
                        ->icon('heroicon-o-banknotes')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('finance.company_name')
                                        ->label(__('order_finance.company_name'))
                                        ->weight(FontWeight::SemiBold)
                                        ->icon('heroicon-o-building-office'),

                                    TextEntry::make('finance.count')
                                        ->label(function (Order $record): string {
                                            return $record->getProductCountLabel();
                                        })
                                        ->icon('heroicon-o-calculator')
                                        ->numeric(),

                                    TextEntry::make('finance.capacity')
                                        ->label(function (Order $record): string {
                                            return $record->getProductCapacityLabel();
                                        })
                                        ->icon('heroicon-o-cube'),

                                    TextEntry::make('finance.execution_duration')
                                        ->label(__('order_finance.execution_duration'))
                                        ->suffix(' '.__('order_finance.days'))
                                        ->icon('heroicon-o-clock')
                                        ->numeric(),

                                    TextEntry::make('total_operation_cost')
                                        ->label(__('order_finance.operation_cost'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->icon('heroicon-o-cog')
                                        ->visible(fn ($record) => $record->shouldShowOperationCost())
                                        ->helperText(__('order_finance.operation_cost_helper')),

                                    TextEntry::make('finance.approved_price')
                                        ->label(__('order_finance.total_approved_price'))
                                        ->numeric(2)
                                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                        ->weight(FontWeight::Bold)
                                        ->size('lg')
                                        ->color('success')
                                        ->icon('heroicon-o-check-circle')
                                        ->helperText(__('order_finance.approved_price_helper')),
                                ]),
                        ])
                        ->visible(fn ($record) => $record->finance !== null),

                    // Order Donor Financial Portfolios Card
                    Section::make(__('order.donor_financial_portfolios'))
                        ->icon('heroicon-o-user-group')
                        ->schema([
                            TextEntry::make('donorFinancialPortfolios')
                                ->label(__('order.portfolio_allocations'))
                                ->listWithLineBreaks()
                                ->bulleted()
                                ->formatStateUsing(function ($state): string {

                                    return $state->name.' - '.number_format($state->pivot->allocated_amount, 2).new HtmlString('<span class="icon-saudi_riyal"></span>');
                                })
                                ->html()
                                ->columnSpanFull(),
                        ])
                        ->visible(fn ($record) => $record->shouldShowOperationCost()),

                ]),
        ])
            ->from('lg')
            ->columnSpan('full');
    }
}
