<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationOrderResource\Pages;

use App\Filament\AssociationAdmin\Resources\AssociationOrderResource;
use App\Models\Order;
use Carbon\Carbon;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\Split;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Infolists\Infolist;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Support\HtmlString;

class AssociationViewOrder extends ViewRecord
{
    protected static string $resource = AssociationOrderResource::class;

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

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

    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 => AssociationOrderResource::getAssociationOrderStatuses()[$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',
                                }),

                            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('number_of_families')
                                        ->label(__('order.number_of_families'))
                                        ->icon('heroicon-o-user-group')
                                        ->numeric(),

                                    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->getAgreementFile()?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                            __('order_agreement.download_agreement_file').'</a>')),
                                ]),
                        ])
                        ->visible(fn ($record) => $record->agreement !== null),

                ]),

            // Second Column
            Grid::make(1)
                ->schema([
                    // 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),

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