<?php

namespace App\Filament\Resources;

use App\Filament\Exports\OrderExporter;
use App\Filament\Resources\OrderResource\Pages;
use App\Models\Order;
use App\Models\OrderRequirement;
use App\Models\State;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class OrderResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = Order::class;

    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static ?int $navigationSort = 1;

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->filterByTypePermissions();
    }

    public static function getModelLabel(): string
    {
        return __('order.order');
    }

    public static function getPluralModelLabel(): string
    {
        return __('order.orders');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.association_management');
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',

            // Order Management approvals
            'request_order_recommendation',
            'provide_order_recommendation',
            'request_technical_financial_proposal',
            'approve_technical_financial_proposal',
            'approve_project_manager',
            'handle_classification',
            'handle_agreement',
            'approve_ceo',
            'launch_project',
            'accept_order',

            // Order Requirements
            'accept_order_requirement',
            'reject_order_requirement',
            'delete_order_requirement',
            'upload_order_requirement_file',

            // tabs list permissions
            'view_all_orders',
            'view_created_orders',
            'view_pending_recommendation_orders',
            'view_recommended_orders',
            'view_technical_financial_requested_orders',
            'view_technical_financial_approved_orders',
            'view_project_manager_approved_orders',
            'view_classification_orders',
            'view_agreement_orders',
            'view_ceo_approved_orders',
            'view_launched_orders',
            'view_accepted_orders',
            'view_rejected_orders',

            // Order type permissions
            'view_all_order_types',
            'view_station_order_type',
            'view_tanker_order_type',
            'view_domestic_storage_tank_order_type',
            'view_central_storage_tank_order_type',
            'view_maintenance_station_order_type',
            'view_maintenance_tanker_order_type',
            'view_micro_network_order_type',
            'view_other_order_type',
            'view_well_drilling_order_type',
            'view_rainwater_storage_order_type',
            'view_home_filters_order_type',
            'view_water_bottles_order_type',
            'view_coolers_order_type',
            'view_products_under_review_order_type',
            'view_well_purification_licenses_order_type',
        ];
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('order.order_information'))
                    ->schema(static::getOrderInformationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('order.location_information'))
                    ->schema(static::getLocationInformationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('order.water_source_information'))
                    ->schema(static::getWaterSourceInformationFields())
                    ->columns(2),

                Forms\Components\Section::make(__('order.project_details'))
                    ->schema(static::getProjectDetailsFields())
                    ->columns(1),

                Forms\Components\Section::make(__('order.required_files'))
                    ->schema(function (Get $get) {
                        return static::getRequiredFilesFields($get);
                    })
                    ->collapsed(false),

                Forms\Components\Section::make(__('order_finance.order_finance'))
                    ->schema(function (Get $get) {
                        return static::getOrderFinanceFields($get);
                    })
                    ->columns(2)
                    ->visible(function (Get $get) {
                        return static::shouldShowFinanceSection($get);
                    })
                    ->collapsed(false),

                Forms\Components\Section::make(__('order_agreement.order_agreement'))
                    ->schema(function (Get $get) {
                        return static::getOrderAgreementFields($get);
                    })
                    ->columns(2)
                    ->visible(function (Get $get) {
                        return static::shouldShowAgreementSection($get);
                    })
                    ->collapsed(false),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([

                Tables\Columns\TextColumn::make('id')
                    ->label(__('order.order_number'))
                    ->badge()
                    ->color('gray')
                    ->prefix('#')
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('association.name')
                    ->searchable()
                    ->sortable()
                    ->label(__('order.association'))
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->association?->name)
                    ->toggleable(),

                Tables\Columns\BadgeColumn::make('type')
                    ->colors([
                        'primary' => Order::TYPE_STATION,
                        'success' => Order::TYPE_TANKER,
                        'warning' => Order::TYPE_DOMESTIC_STORAGE_TANK,
                        'info' => Order::TYPE_CENTRAL_STORAGE_TANK,
                        'secondary' => Order::TYPE_MAINTENANCE_STATION,
                        'danger' => Order::TYPE_MAINTENANCE_TANKER,
                        'primary' => Order::TYPE_MICRO_NETWORK,
                        'gray' => Order::TYPE_OTHER,
                        'success' => Order::TYPE_WELL_DRILLING,
                        'info' => Order::TYPE_RAINWATER_STORAGE,
                        'warning' => Order::TYPE_HOME_FILTERS,
                        'secondary' => Order::TYPE_WATER_BOTTLES,
                        'primary' => Order::TYPE_COOLERS,
                        'gray' => Order::TYPE_PRODUCTS_UNDER_REVIEW,
                    ])
                    ->label(__('order.order_type'))
                    ->formatStateUsing(fn (string $state): string => __(Order::getAllOrderTypes()[$state] ?? $state))
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\BadgeColumn::make('status')
                    ->colors([
                        'warning' => Order::STATUS_CREATED,
                        'primary' => Order::STATUS_PENDING_RECOMMENDATION,
                        'success' => Order::STATUS_RECOMMENDED,
                        'info' => Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED,
                        'info' => Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
                        'secondary' => Order::STATUS_PROJECT_MANAGER_APPROVED,
                        'primary' => Order::STATUS_CLASSIFICATION,
                        'secondary' => Order::STATUS_AGREEMENT,
                        'info' => Order::STATUS_CEO_APPROVED,
                        'gray' => Order::STATUS_LAUNCHED,
                        'success' => Order::STATUS_ACCEPTED,
                        'danger' => Order::STATUS_REJECTED,
                    ])
                    ->formatStateUsing(fn (string $state): string => __(Order::getOrderStatuses()[$state] ?? $state))
                    ->label(__('order.status'))
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('state.name')
                    ->label(__('order.state'))
                    ->searchable()
                    ->toggleable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->state?->name),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('order.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label(__('order.order_type'))
                    ->options(collect(Order::getOrderTypes())->mapWithKeys(fn ($value, $key) => [$key => __($value)])),
                // filter by state
                Tables\Filters\SelectFilter::make('state_id')
                    ->label(__('order.state'))
                    ->options(collect(State::all())->mapWithKeys(fn ($state) => [$state->id => $state->name])),
            ])
            ->headerActions([
                ExportAction::make()
                    ->exporter(OrderExporter::class),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            OrderResource\RelationManagers\RequirementsRelationManager::class,
            // OrderResource\RelationManagers\DonorFinancialPortfoliosRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListOrders::route('/'),
            'create' => Pages\CreateOrder::route('/create'),
            'view' => Pages\ViewOrder::route('/{record}'),
            'edit' => Pages\EditOrder::route('/{record}/edit'),
        ];
    }

    /**
     * Get the order information form fields
     */
    public static function getOrderInformationFields(): array
    {
        return [
            Forms\Components\Select::make('association_id')
                ->label(__('order.association'))
                ->relationship('association', 'name')
                ->required()
                ->searchable()
                ->preload(),

            Forms\Components\Select::make('type')
                ->required()
                ->options(collect(Order::getOrderTypes())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->default(Order::TYPE_STATION)
                ->label(__('order.order_type'))
                ->live()
                ->afterStateUpdated(function (Set $set, $state) {
                    // Clear files when type changes
                    $requirements = Order::getTypeFileRequirements()[$state] ?? [];
                    foreach ($requirements as $fileKey => $fileTitle) {
                        $set($fileKey, null);
                    }
                }),

            // status
            Forms\Components\Select::make('status')
                ->label(__('order.status'))
                ->options(collect(Order::getOrderStatuses())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->default(Order::STATUS_PENDING_RECOMMENDATION)
                ->required()
                ->searchable()
                ->preload(),

            Forms\Components\Hidden::make('created_by')
                ->default(fn () => Auth::id()),
        ];
    }

    /**
     * Get the location information form fields
     */
    public static function getLocationInformationFields(): array
    {
        return [
            Forms\Components\Select::make('state_id')
                ->label(__('order.state'))
                ->relationship(
                    'state',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set) {
                    $set('city_id', null);
                    $set('centers', []);
                })
                ->options(function (Get $get) {
                    return \App\Models\State::pluck('name', 'id');
                }),

            Forms\Components\Select::make('city_id')
                ->label(__('order.city'))
                ->relationship(
                    'city',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->where('state_id', $get('state_id'))
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set, $state, Get $get) {
                    $set('centers', []);

                    // Auto-update map location when city is selected
                    if ($state) {
                        $locationService = app(\App\Services\LocationCoordinatesService::class);
                        $coordinates = $locationService->getCityCoordinates($state);

                        if ($coordinates) {
                            $set('location', $coordinates);
                            $set('lat', $coordinates['lat']);
                            $set('lng', $coordinates['lng']);
                        }
                    }
                }),

            Forms\Components\Select::make('centers')
                ->label(__('order.centers'))
                ->relationship('centers', 'name')
                ->required()
                ->multiple()
                ->searchable()
                ->getSearchResultsUsing(
                    fn (string $search, Get $get): array => \App\Models\Center::where('city_id', $get('city_id'))
                        ->where('name', 'like', "%{$search}%")
                        ->pluck('name', 'id')
                        ->toArray()
                )
                ->preload()
                ->live()
                ->options(function (Get $get) {
                    $cityId = $get('city_id');
                    if (! $cityId) {
                        return [];
                    }

                    return \App\Models\Center::where('city_id', $cityId)->pluck('name', 'id');
                })
                ->afterStateUpdated(function (Set $set, $state, Get $get) {
                    $set('residentialGatherings', []);
                }),

            Forms\Components\Select::make('residentialGatherings')
                ->label(__('order.residential_gatherings'))
                ->helperText(__('order.residential_gatherings_helper'))
                ->relationship('residentialGatherings', 'name')
                ->multiple()
                ->searchable()
                ->getSearchResultsUsing(function (string $search, Get $get): array {
                    $centerIds = $get('centers');
                    if (empty($centerIds)) {
                        return [];
                    }

                    return \App\Models\ResidentialGathering::whereIn('center_id', $centerIds)
                        ->where('name', 'like', "%{$search}%")
                        ->with('center')
                        ->get()
                        ->mapWithKeys(function ($rg) {
                            return [$rg->id => $rg->name.' ('.$rg->center->name.')'];
                        })
                        ->toArray();
                })
                ->getOptionLabelFromRecordUsing(fn ($record) => $record->name.' ('.$record->center->name.')')
                ->preload()
                ->options(function (Get $get) {
                    $centerIds = $get('centers');
                    if (empty($centerIds)) {
                        return [];
                    }

                    return \App\Models\ResidentialGathering::whereIn('center_id', $centerIds)
                        ->with('center')
                        ->get()
                        ->mapWithKeys(function ($rg) {
                            return [$rg->id => $rg->name.' ('.$rg->center->name.')'];
                        })
                        ->toArray();
                }),

            Map::make('location')
                ->label(__('order.location'))
                ->mapControls([
                    'mapTypeControl' => true,
                    'scaleControl' => true,
                    'streetViewControl' => true,
                    'rotateControl' => true,
                    'fullscreenControl' => true,
                    'searchBoxControl' => false,
                    'zoomControl' => true,
                ])
                ->height(fn () => '400px')
                ->defaultZoom(8)
                // default location to riyadh
                ->defaultLocation([24.7136, 46.6753])
                ->autocomplete('address')
                ->clickable(true)
                ->reactive()
                ->afterStateUpdated(function (Set $set, $state) {
                    if (is_array($state) && isset($state['lat']) && isset($state['lng'])) {
                        $set('lat', $state['lat']);
                        $set('lng', $state['lng']);
                    }
                })
                ->afterStateHydrated(function (Set $set, $state, $record) {
                    if ($record && $record->lat && $record->lng) {
                        $set('location', [
                            'lat' => (float) $record->lat,
                            'lng' => (float) $record->lng,
                        ]);
                    }
                })
                ->columnSpanFull(),

            Forms\Components\Hidden::make('lat'),
            Forms\Components\Hidden::make('lng'),

            Forms\Components\TextInput::make('number_of_families')
                ->label(__('order.number_of_families'))
                ->required()
                ->numeric()
                ->minValue(1),
        ];
    }

    /**
     * Get the water source information form fields
     */
    public static function getWaterSourceInformationFields(): array
    {
        return [
            Forms\Components\Select::make('water_source')
                ->label(__('order.water_source'))
                ->required()
                ->multiple()
                ->options(collect(Order::getWaterSources())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->helperText(__('order.water_source_helper')),

            Forms\Components\TextInput::make('water_distance')
                ->label(__('order.water_distance'))
                ->required()
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('order.km_suffix')),
        ];
    }

    /**
     * Get the project details form fields
     */
    public static function getProjectDetailsFields(): array
    {
        return [
            Forms\Components\Select::make('development_impacts')
                ->label(__('order.development_impacts'))
                ->multiple()
                ->relationship(
                    'developmentImpacts',
                    'name',
                    fn (Builder $query) => $query->where('type', \App\Models\SekayaValue::TYPE_ORDER_IMPACT_REASONS)
                )
                ->preload()
                ->searchable()
                ->required(),

            Forms\Components\Textarea::make('order_justifications')
                ->label(__('order.order_justifications'))
                ->required()
                ->rows(3)
                ->maxLength(1000),

            Forms\Components\Textarea::make('order_description')
                ->label(__('order.order_description'))
                ->required()
                ->rows(3)
                ->maxLength(1000)
                ->helperText(__('order.order_description_helper')),
        ];
    }

    /**
     * Get the required files form fields
     */
    public static function getRequiredFilesFields(Get $get): array
    {
        $type = $get('type');
        if (! $type) {
            return [
                Forms\Components\Placeholder::make('select_type_first')
                    ->label('')
                    ->content(__('order.select_type_first')),
            ];
        }

        $requirements = Order::getTypeFileRequirements()[$type] ?? [];

        if (empty($requirements)) {
            return [
                Forms\Components\Placeholder::make('no_files_required')
                    ->label('')
                    ->content(__('order.no_files_required')),
            ];
        }

        $fields = [];

        if ($type === ORDER::TYPE_STATION) {
            // show a guidance link for station type with specific URL
            $fields[] = Forms\Components\Placeholder::make('station_guide_file_helper')
                ->label(__('order.station_guide_file_helper'))
                ->content(new \Illuminate\Support\HtmlString(
                    ' <a href="'.'https://sekaya-prod-api.fra1.digitaloceanspaces.com/sekaya-templates/%D8%A7%D9%84%D8%A7%D8%B4%D8%AA%D8%B1%D8%A7%D8%B7%D8%A7%D8%AA%20%D9%88%20%D8%A7%D9%84%D9%85%D9%88%D8%A7%D8%B5%D9%81%D8%A7%D8%AA%20%D9%84%D8%AA%D9%82%D8%AF%D9%8A%D9%85%20%20%D9%85%D8%B4%D8%B1%D9%88%D8%B9%20%D9%85%D8%AD%D8%B7%D8%A9%20%D8%AA%D9%86%D9%82%D9%8A%D8%A9%20%D9%85%D9%8A%D8%A7%D9%87%202025.pdf'.'" target="_blank" class="text-primary-600 hover:text-primary-500 underline">'.__('common.click_to_download').'</a>'
                )
                );
        }

        foreach ($requirements as $fileKey => $fileData) {
            $field = SpatieMediaLibraryFileUpload::make($fileKey)
                ->label(__($fileData['label']))
                ->visibility('private')
                ->required($fileData['required'] ?? false)
                ->directory('orders')
                ->collection('order_files')
                ->acceptedFileTypes([
                    'application/pdf',
                    'image/jpeg',
                    'image/png',
                    'image/jpg',
                ])
                ->customProperties([
                    'file_title' => __($fileData['label']),
                ])
                ->downloadable()
                ->maxSize(10240); // 10MB

            // Add guidance link if file_url is provided
            if (! empty($fileData['file_url'])) {
                $field->helperText(
                    new \Illuminate\Support\HtmlString(
                        __('order.file_guidance_available').' <a href="'.$fileData['file_url'].'" target="_blank" class="text-primary-600 hover:text-primary-500 underline">'.__('order.download_guidance').'</a>'
                    )
                );
            }

            $fields[] = $field;
        }

        return $fields;
    }

    /**
     * Check if the finance section should be shown (read-only, after TECHNICAL_FINANCIAL_APPROVED)
     */
    public static function shouldShowFinanceSection(Get $get): bool
    {
        $status = $get('status');
        if (! $status) {
            return false;
        }

        // Define the statuses that should show the finance section (after TECHNICAL_FINANCIAL_APPROVED)
        $financeStatuses = [
            Order::STATUS_PROJECT_MANAGER_APPROVED,
            Order::STATUS_CLASSIFICATION,
            Order::STATUS_AGREEMENT,
            Order::STATUS_CEO_APPROVED,
            Order::STATUS_LAUNCHED,
            Order::STATUS_ACCEPTED,
        ];

        return in_array($status, $financeStatuses);
    }

    /**
     * Get the order finance form fields (read-only for display)
     */
    public static function getOrderFinanceFields(Get $get): array
    {
        if (! static::shouldShowFinanceSection($get)) {
            return [];
        }

        return [
            Forms\Components\Fieldset::make(__('order_finance.order_finance'))
                ->relationship('finance')
                ->schema([
                    Forms\Components\TextInput::make('count')
                        ->label(__('order_finance.count'))
                        ->numeric()
                        ->helperText(__('order_finance.count_helper')),

                    Forms\Components\TextInput::make('capacity')
                        ->label(__('order_finance.capacity'))
                        ->maxLength(255)
                        ->helperText(__('order_finance.capacity_helper')),

                    Forms\Components\TextInput::make('execution_duration')
                        ->label(__('order_finance.execution_duration'))
                        ->numeric()
                        ->suffix(__('order_finance.days'))
                        ->helperText(__('order_finance.execution_duration_helper')),

                    Forms\Components\TextInput::make('company_name')
                        ->label(__('order_finance.company_name'))
                        ->maxLength(255)
                        ->helperText(__('order_finance.company_name_helper')),

                    Forms\Components\Select::make('order_requirement_id')
                        ->label(__('order.approved_order_requirement'))
                        ->options(function (Get $get) {
                            $record = $get('../../record') ?? $get('../record');
                            if ($record) {
                                return $record->requirements()
                                    ->where('status', OrderRequirement::STATUS_ACCEPTED)
                                    ->pluck('name', 'id')
                                    ->toArray();
                            }

                            return [];
                        })
                        ->searchable(),

                    Forms\Components\Grid::make(2)
                        ->schema([
                            Forms\Components\TextInput::make('offer_price')
                                ->label(__('order_finance.offer_price'))
                                ->numeric()
                                ->step(0.01)
                                ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                ->live()
                                ->helperText(__('order_finance.offer_price_helper')),

                            Forms\Components\TextInput::make('additional_fees')
                                ->label(__('order_finance.additional_fees'))
                                ->numeric()
                                ->step(0.01)
                                ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                ->live()
                                ->helperText(__('order_finance.additional_fees_helper')),
                        ]),

                    Forms\Components\Placeholder::make('approved_price')
                        ->label(__('order_finance.approved_price'))
                        ->content(function (Forms\Get $get) {
                            $offerPrice = $get('offer_price');
                            $additionalFees = $get('additional_fees');

                            return $offerPrice + $additionalFees;
                        })
                        ->helperText(__('order_finance.approved_price_helper')),

                    Forms\Components\Hidden::make('operation_cost_percentage')
                        ->default(fn () => 0),
                ]),

        ];
    }

    /**
     * Get the order agreement form fields (read-only for display)
     */
    public static function getOrderAgreementFields(Get $get): array
    {
        if (! static::shouldShowAgreementSection($get)) {
            return [];
        }

        return [
            Forms\Components\Fieldset::make(__('order_agreement.order_agreement'))
                ->relationship('agreement')
                ->schema([
                    Forms\Components\TextInput::make('contract_number')
                        ->label(__('order_agreement.contract_number'))
                        ->maxLength(255)
                        ->unique(table: 'order_agreements', column: 'contract_number', ignoreRecord: true)
                        ->helperText(__('order_agreement.contract_number_helper')),

                    Forms\Components\TextInput::make('total_contract_value')
                        ->label(__('order_agreement.total_contract_value'))
                        // set default value to the approved price from finance
                        ->default(function (Order $record) {
                            return $record->finance?->approved_price ?? 0;
                        })
                        ->readOnly()
                        ->numeric()
                        ->step(0.01)
                        ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                        ->helperText(__('order_agreement.total_contract_value_helper')),

                    Forms\Components\DatePicker::make('start_date')
                        ->label(__('order_agreement.start_date'))
                        ->live()
                        ->afterStateUpdated(function (Forms\Set $set, $state, Forms\Get $get) {
                            $record = $get('../../record') ?? $get('../record');
                            if ($state && $record && $record->finance?->execution_duration) {
                                $startDate = \Carbon\Carbon::parse($state);
                                $endDate = $startDate->addDays($record->finance->execution_duration);
                                $set('calculated_end_date', $endDate->format('Y-m-d'));
                            }
                        })
                        ->helperText(__('order_agreement.start_date_helper')),

                    Forms\Components\Hidden::make('calculated_end_date'),

                    Forms\Components\Placeholder::make('end_date_display')
                        ->label(__('order_agreement.end_date'))
                        ->content(function (Forms\Get $get) {
                            $record = $get('../../record') ?? $get('../record');
                            $calculatedEndDate = $get('calculated_end_date');
                            if ($calculatedEndDate) {
                                return \Carbon\Carbon::parse($calculatedEndDate)->format('Y-m-d');
                            }

                            $startDate = $get('start_date');
                            if ($startDate && $record && $record->finance?->execution_duration) {
                                $start = \Carbon\Carbon::parse($startDate);
                                $end = $start->addDays($record->finance->execution_duration);

                                return $end->format('Y-m-d');
                            }

                            return __('order_agreement.not_calculated');
                        })
                        ->helperText(function (Forms\Get $get) {
                            $record = $get('../../record') ?? $get('../record');

                            return __('order_agreement.end_date_helper').' ('.($record && $record->finance?->execution_duration ? $record->finance->execution_duration : 0).' '.__('order_finance.days').')';
                        }),

                ]),
            Forms\Components\SpatieMediaLibraryFileUpload::make('order_agreement.agreement_file')
                ->label(__('order_agreement.agreement_file'))
                ->collection('agreement_file')
                ->visibility('private')
                ->directory('order-agreements')
                ->acceptedFileTypes(['application/pdf'])
                ->downloadable()
                ->maxSize(10240) // 10MB
                ->helperText(__('order_agreement.agreement_file_helper'))
                ->columnSpanFull(),
        ];
    }

    /**
     * Check if the agreement section should be shown
     */
    protected static function shouldShowAgreementSection(Get $get): bool
    {
        $record = $get('../../record') ?? $get('../record');

        return $record && $record->agreement;
    }
}
