<?php

namespace App\Filament\Resources;

use App\Enums\OrderCarrier;
use App\Enums\OrderChannel;
use App\Enums\OrderDetailStatus;
use App\Enums\OrderStatus;
use App\Enums\OrderType;
use App\Filament\Resources\OrderResource\Pages;
use App\Mail\OrderStatusMail;
use App\Models\OrderCarrierCatalog;
use App\Models\OrderChannelCatalog;
use App\Models\OrderStatusCatalog;
use App\Models\OrderTypeCatalog;
use App\Models\Order;
use App\Models\Province;
use App\Models\Canton;
use App\Models\District;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Actions\Action as NotificationAction;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\ViewColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Services\Shipping\ShippingService;

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

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

    protected static ?string $navigationGroup = 'Gestión de Pedidos';

    protected static ?int $navigationSort = 1;

    public static function shouldRegisterNavigation(): bool
    {
        return false;
    }

    protected static ?string $slug = 'ordenes';

    public static function getModelLabel(): string
    {
        return 'Orden';
    }

    public static function getPluralModelLabel(): string
    {
        return 'Órdenes';
    }

    public static function getNavigationLabel(): string
    {
        return 'Órdenes';
    }

    public static function getModuleDescription(): string
    {
        return 'Visualiza y gestiona centralizadamente las órdenes recibidas (Shopify y otros canales) para monitorear su procesamiento logístico durante todo el ciclo de vida.';
    }

    public static function canViewAny(): bool
    {
        return auth()->user()?->can('orders.view') ?? false;
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('orders.create') ?? false;
    }

    public static function canEdit($record): bool
    {
        return auth()->user()?->can('orders.update') ?? false;
    }

    public static function canDelete($record): bool
    {
        return false;
    }

    public static function canDeleteAny(): bool
    {
        return false;
    }

    public static function getEloquentQuery(): Builder
    {
        return static::applyStoreScope(
            static::applyDetailCounts(parent::getEloquentQuery())
        );
    }

    protected static function applyDetailCounts(Builder $query): Builder
    {
        return $query->withCount([
            'details as total_items_count',
            'details as finalized_items_count' => fn (Builder $detailQuery): Builder => $detailQuery
                ->whereIn('current_status', OrderDetailStatus::terminalValues()),
        ]);
    }

    protected static function applyStoreScope(Builder $query): Builder
    {
        $user = auth()->user();
        if (! $user) {
            return $query->whereRaw('1=0');
        }

        if (method_exists($user, 'hasRole') && $user->hasRole('administrador')) {
            return $query;
        }

        $storeIds = $user->stores()->pluck('tbl_stores.id');
        if ($storeIds->isEmpty()) {
            return $query->whereRaw('1=0');
        }

        return $query->whereIn('store_id', $storeIds);
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Placeholder::make('terminal_state_notice')
                    ->label('')
                    ->content('Esta orden se encuentra en un estado final y no puede ser modificada.')
                    ->visible(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->columnSpanFull(),

                Forms\Components\Section::make('Progreso')
                    ->visible(fn (string $context): bool => $context !== 'create')
                    ->schema([
                        Forms\Components\ViewField::make('order_progress')
                            ->label('')
                            ->view('filament.orders.forms.order-progress')
                            ->dehydrated(false),
                    ]),

                Forms\Components\Section::make('Orden')
                    ->columns(3)
                    ->disabled(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->schema([
                        Forms\Components\TextInput::make('order_reference')
                            ->label('Referencia')
                            ->default(fn () => Str::upper(Str::random(9)))
                            ->required()
                            ->maxLength(9)
                            ->readOnly(),
                        Forms\Components\Select::make('store_id')
                            ->label('Tienda')
                            ->relationship('store', 'name', modifyQueryUsing: function (Builder $query): Builder {
                                $user = auth()->user();
                                if (! $user) {
                                    return $query->whereRaw('1=0');
                                }

                                if (method_exists($user, 'hasRole') && $user->hasRole('administrador')) {
                                    return $query;
                                }

                                $storeIds = $user->stores()->pluck('tbl_stores.id');
                                if ($storeIds->isEmpty()) {
                                    return $query->whereRaw('1=0');
                                }

                                return $query->whereIn('tbl_stores.id', $storeIds);
                            })
                            ->searchable()
                            ->preload(),
                        Forms\Components\TextInput::make('guide')
                            ->label('Guía')
                            ->maxLength(255),

                        Forms\Components\Select::make('channel_id')
                            ->label('Canal')
                            ->relationship('channelCatalog', 'name')
                            ->searchable()
                            ->preload()
                            ->default(fn () => OrderChannelCatalog::query()
                                ->where('code', OrderChannel::Manual->value)
                                ->value('id_order_channel'))
                            ->required(),
                        Forms\Components\Select::make('order_type_id')
                            ->label('Tipo de orden')
                            ->relationship('orderTypeCatalog', 'name')
                            ->searchable()
                            ->preload()
                            ->default(fn () => OrderTypeCatalog::query()
                                ->where('code', OrderType::Reshipment->value)
                                ->value('id_order_type'))
                            ->required()
                            ->disabled(fn (string $context) => $context === 'create')
                            ->dehydrated(),
                        Forms\Components\Select::make('status_id')
                            ->label('Estado actual')
                            ->relationship(
                                name: 'statusCatalog',
                                titleAttribute: 'name',
                                modifyQueryUsing: fn (Builder $query): Builder => $query
                                    ->active()
                                    ->visibleInStatusSelectors()
                                    ->orderBy('name'),
                            )
                            ->searchable()
                            ->preload()
                            ->default(fn () => OrderStatusCatalog::query()
                                ->where('code', OrderStatus::Ingresado->value)
                                ->value('id_order_status'))
                            ->required(),

                        Forms\Components\Select::make('carrier_id')
                            ->label('Carrier')
                            ->relationship('carrierCatalog', 'name')
                            ->searchable()
                            ->preload()
                            ->nullable(),
                        Forms\Components\DateTimePicker::make('date_order')
                            ->label('Fecha de ingreso')
                            ->default(now())
                            ->required(),
                        Forms\Components\TextInput::make('payment')
                            ->label('Método de pago')
                            ->maxLength(255),

                        Forms\Components\Select::make('original_order_reference')
                            ->label('Orden original (para redespacho)')
                            ->helperText('Requerido al crear un redespacho.')
                            ->searchable()
                            ->disabled(fn (Forms\Get $get) => filled($get('original_order_reference')))
                            ->dehydrated()
                            ->options(fn () => Order::query()
                                ->orderByDesc('date_order')
                                ->limit(200)
                                ->pluck('order_reference', 'order_reference')
                                ->all())
                            ->required(fn (string $context) => $context === 'create'),
                    ]),

                Forms\Components\Section::make('Cliente')
                    ->columns(3)
                    ->disabled(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->schema([
                        Forms\Components\TextInput::make('codClient')
                            ->label('Código cliente')
                            ->required()
                            ->maxLength(50),
                        Forms\Components\TextInput::make('customer_name')
                            ->label('Nombre')
                            ->maxLength(255),
                        Forms\Components\TextInput::make('customer_identification')
                            ->label('Cédula')
                            ->maxLength(255),
                        Forms\Components\TextInput::make('customer_email')
                            ->label('Correo')
                            ->email()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('customer_phone')
                            ->label('Teléfono')
                            ->maxLength(255),
                        Forms\Components\TextInput::make('customer_legal_activity')
                            ->label('Actividad jurídica')
                            ->maxLength(255),
                        Forms\Components\TextInput::make('customer_total_orders')
                            ->label('Total de pedidos')
                            ->numeric()
                            ->minValue(1)
                            ->default(1),
                    ]),

                Forms\Components\Section::make('Dirección')
                    ->columns(3)
                    ->disabled(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->schema([
                        Forms\Components\TextInput::make('postal_code')
                            ->label('Código postal')
                            ->maxLength(255),
                        Forms\Components\Select::make('province_id')
                            ->label('Provincia')
                            ->options(fn () => Province::query()->orderBy('name')->pluck('name', 'id_province')->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (Forms\Set $set) {
                                $set('canton_id', null);
                                $set('district_id', null);
                            }),
                        Forms\Components\Select::make('canton_id')
                            ->label('Cantón')
                            ->native(false)
                            ->options(function (Forms\Get $get) {
                                $provinceId = $get('province_id');
                                if (blank($provinceId)) {
                                    return [];
                                }

                                $options = Canton::query()
                                    ->where('province_id', $provinceId)
                                    ->orderBy('name')
                                    ->pluck('name', 'id_canton')
                                    ->all();

                                if (
                                    empty($options)
                                    && Schema::hasColumn('tbl_cantons', 'id_province')
                                ) {
                                    $options = Canton::query()
                                        ->where('id_province', $provinceId)
                                        ->orderBy('name')
                                        ->pluck('name', 'id_canton')
                                        ->all();
                                }

                                return $options;
                            })
                            ->preload()
                            ->live()
                            ->disabled(fn (Forms\Get $get) => blank($get('province_id')))
                            ->afterStateUpdated(fn (Forms\Set $set) => $set('district_id', null)),
                        Forms\Components\Select::make('district_id')
                            ->label('Distrito')
                            ->native(false)
                            ->options(function (Forms\Get $get) {
                                $cantonId = $get('canton_id');
                                if (blank($cantonId)) {
                                    return [];
                                }

                                $options = District::query()
                                    ->where('canton_id', $cantonId)
                                    ->orderBy('name')
                                    ->pluck('name', 'id_district')
                                    ->all();

                                if (
                                    empty($options)
                                    && Schema::hasColumn('tbl_districts', 'id_canton')
                                ) {
                                    $options = District::query()
                                        ->where('id_canton', $cantonId)
                                        ->orderBy('name')
                                        ->pluck('name', 'id_district')
                                        ->all();
                                }

                                return $options;
                            })
                            ->preload()
                            ->live()
                            ->disabled(fn (Forms\Get $get) => blank($get('canton_id'))),
                        Forms\Components\Textarea::make('address_detail')
                            ->label('Dirección detallada')
                            ->rows(2)
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make('Detalle de compra')
                    ->disabled(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->schema([
                        Forms\Components\Repeater::make('details')
                            ->relationship('details')
                            ->label('Productos')
                            ->defaultItems(1)
                            ->minItems(1)
                            ->schema([
                                Forms\Components\TextInput::make('product_reference')
                                    ->label('Código / SKU')
                                    ->required()
                                    ->maxLength(64),
                                Forms\Components\TextInput::make('product_name')
                                    ->label('Descripción')
                                    ->required(),
                                Forms\Components\TextInput::make('warehouse_assigned')
                                    ->label('Bodega asignada')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('product_quantity')
                                    ->label('Cantidad')
                                    ->numeric()
                                    ->minValue(1)
                                    ->default(1)
                                    ->required()
                                    ->reactive()
                                    ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set) {
                                        $qty = (int) ($get('product_quantity') ?? 0);
                                        $priceTI = (float) ($get('product_priceTI') ?? 0);
                                        $priceTE = (float) ($get('product_priceTE') ?? 0);

                                        $set('total_priceTI', $qty * $priceTI);
                                        $set('total_priceTE', $qty * $priceTE);
                                    }),
                                Forms\Components\TextInput::make('product_tax')
                                    ->label('Impuesto %')
                                    ->numeric()
                                    ->default(13)
                                    ->required(),
                                Forms\Components\TextInput::make('product_priceTI')
                                    ->label('Precio unitario (TI)')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->default(0)
                                    ->required()
                                    ->reactive()
                                    ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set) {
                                        $qty = (int) ($get('product_quantity') ?? 0);
                                        $priceTI = (float) ($get('product_priceTI') ?? 0);

                                        $set('total_priceTI', $qty * $priceTI);
                                    }),
                                Forms\Components\TextInput::make('product_priceTE')
                                    ->label('Precio unitario (TE)')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->default(0)
                                    ->required()
                                    ->reactive()
                                    ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set) {
                                        $qty = (int) ($get('product_quantity') ?? 0);
                                        $priceTE = (float) ($get('product_priceTE') ?? 0);

                                        $set('total_priceTE', $qty * $priceTE);
                                    }),
                                Forms\Components\TextInput::make('total_priceTI')
                                    ->label('Total (TI)')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->readOnly()
                                    ->dehydrated(),
                                Forms\Components\TextInput::make('total_priceTE')
                                    ->label('Total (TE)')
                                    ->numeric()
                                    ->prefix('₡')
                                    ->readOnly()
                                    ->dehydrated(),
                            ])
                            ->columns(4)
                            ->reorderable(false)
                            ->addActionLabel('Agregar producto')
                            ->deleteAction(
                                fn (Forms\Components\Actions\Action $action) => $action->label('Excluir')
                            ),
                    ]),

                Forms\Components\Section::make('Totales')
                    ->columns(3)
                    ->disabled(fn (string $context, ?Order $record): bool => $context !== 'create' && ($record?->isTerminalState() ?? false))
                    ->schema([
                        Forms\Components\TextInput::make('total_productsTI')
                            ->label('Total productos (TI)')
                            ->numeric()
                            ->prefix('₡')
                            ->readOnly(),
                        Forms\Components\TextInput::make('total_productsTE')
                            ->label('Total productos (TE)')
                            ->numeric()
                            ->prefix('₡')
                            ->readOnly(),
                        Forms\Components\TextInput::make('total_shipping')
                            ->label('Envío')
                            ->numeric()
                            ->prefix('₡')
                            ->default(0),
                        Forms\Components\TextInput::make('total_discounts')
                            ->label('Descuentos')
                            ->numeric()
                            ->prefix('₡')
                            ->default(0),
                        Forms\Components\TextInput::make('total_paidTI')
                            ->label('Total pagado (TI)')
                            ->numeric()
                            ->prefix('₡')
                            ->readOnly(),
                        Forms\Components\TextInput::make('total_paidTE')
                            ->label('Total pagado (TE)')
                            ->numeric()
                            ->prefix('₡')
                            ->readOnly(),
                    ]),

                Forms\Components\Section::make('Confirmación (redespacho)')
                    ->visible(fn (string $context) => $context === 'create')
                    ->schema([
                        Forms\Components\Checkbox::make('confirm_1')
                            ->label('Confirmo que los productos ajustados son correctos.')
                            ->accepted()
                            ->required(),
                        Forms\Components\Checkbox::make('confirm_2')
                            ->label('Confirmo que el cliente ya fue cobrado y el total refleja el ajuste.')
                            ->accepted()
                            ->required(),
                        Forms\Components\Checkbox::make('confirm_3')
                            ->label('Confirmo que la nueva orden seguirá el flujo normal de preparación.')
                            ->accepted()
                            ->required(),
                    ]),
            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->queryStringIdentifier('orders_list')
            ->modifyQueryUsing(function (Builder $query): Builder {
                $query->with([
                    'channelCatalog',
                    'orderTypeCatalog',
                    'statusCatalog',
                    'carrierCatalog',
                ]);

                $user = auth()->user();
                if (! $user) {
                    return $query->whereRaw('1=0');
                }

                if (method_exists($user, 'hasRole') && $user->hasRole('administrador')) {
                    return $query;
                }

                $storeIds = $user->stores()->pluck('tbl_stores.id');
                if ($storeIds->isEmpty()) {
                    return $query->whereRaw('1=0');
                }

                return $query->whereIn('store_id', $storeIds);
            })
            ->columns([
                Tables\Columns\TextColumn::make('id_order')
                    ->label('Número de orden')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('order_reference')
                    ->label('Referencia')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('origin_badge')
                    ->label('Origen')
                    ->badge()
                    ->state(fn (Order $record): string => filled($record->remote_order_id) ? 'Universal' : 'Local')
                    ->icon(fn (Order $record): string => filled($record->remote_order_id) ? 'heroicon-o-building-storefront' : 'heroicon-o-archive-box')
                    ->color(fn (Order $record): string => filled($record->remote_order_id) ? 'info' : 'gray'),
                Tables\Columns\TextColumn::make('order_type_badge')
                    ->label('Tipo')
                    ->badge()
                    ->state(function (Order $record): string {
                        $code = (string) ($record->orderTypeCatalog?->code ?? $record->order_type ?? '');
                        return $code === OrderType::Reshipment->value ? 'Redespacho' : 'Despacho';
                    })
                    ->color(function (Order $record): string {
                        $code = (string) ($record->orderTypeCatalog?->code ?? $record->order_type ?? '');
                        return $code === OrderType::Reshipment->value ? 'warning' : 'gray';
                    })
                    ->icon(function (Order $record): string {
                        $code = (string) ($record->orderTypeCatalog?->code ?? $record->order_type ?? '');
                        return $code === OrderType::Reshipment->value ? 'heroicon-o-arrow-path' : 'heroicon-o-truck';
                    }),
                Tables\Columns\TextColumn::make('channelCatalog.name')
                    ->label('Canal')
                    ->sortable(query: fn (Builder $query, string $direction): Builder => $query->orderBy('channel_id', $direction))
                    ->searchable(),
                Tables\Columns\TextColumn::make('date_order')
                    ->label('Fecha de ingreso')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('store_name')
                    ->label('Tienda')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('guide')
                    ->label('Guía')
                    ->searchable(),
                Tables\Columns\TextColumn::make('orderTypeCatalog.name')
                    ->label('Tipo de orden')
                    ->sortable(query: fn (Builder $query, string $direction): Builder => $query->orderBy('order_type_id', $direction)),
                Tables\Columns\TextColumn::make('statusCatalog.name')
                    ->label('Estado actual')
                    ->badge()
                    ->color(function (Order $record): string {
                        $code = (string) ($record->statusCatalog?->code ?? $record->status ?? '');
                        if ($code === OrderStatus::Ingresado->value) {
                            return 'success';
                        }

                        return OrderStatus::tryFrom($code)?->filamentColor() ?? 'gray';
                    })
                    ->sortable(query: fn (Builder $query, string $direction): Builder => $query->orderBy('status_id', $direction)),

                ViewColumn::make('progress')
                    ->label('Progreso')
                    ->view('filament.tables.columns.order-progress'),
            ])
            ->filters([
                Tables\Filters\Filter::make('date_order')
                    ->label('Fecha ingreso')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('Desde')
                            ->rule('before_or_equal:until'),
                        Forms\Components\DatePicker::make('until')
                            ->label('Hasta')
                            ->rule('after_or_equal:from'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $q, $date) => $q->whereDate('date_order', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $q, $date) => $q->whereDate('date_order', '<=', $date));
                    }),
                Tables\Filters\SelectFilter::make('status_id')
                    ->label('Estado')
                    ->relationship(
                        'statusCatalog',
                        'name',
                        fn (Builder $query): Builder => $query
                            ->active()
                            ->visibleInStatusSelectors()
                            ->orderBy('name'),
                    )
                    ->placeholder('Todos'),
                Tables\Filters\SelectFilter::make('order_type_id')
                    ->label('Tipo de orden')
                    ->relationship('orderTypeCatalog', 'name')
                    ->placeholder('Todos'),
                Tables\Filters\SelectFilter::make('channel_id')
                    ->label('Canal')
                    ->relationship('channelCatalog', 'name')
                    ->placeholder('Todos'),
                Tables\Filters\SelectFilter::make('store_id')
                    ->label('Tienda')
                    ->relationship('store', 'name', function (Builder $query): Builder {
                        $user = auth()->user();
                        if (! $user) {
                            return $query->whereRaw('1=0');
                        }

                        if (method_exists($user, 'hasRole') && $user->hasRole('administrador')) {
                            return $query;
                        }

                        $storeIds = $user->stores()->pluck('tbl_stores.id');
                        if ($storeIds->isEmpty()) {
                            return $query->whereRaw('1=0');
                        }

                        return $query->whereIn('tbl_stores.id', $storeIds);
                    })
                    ->searchable()
                    ->preload()
                    ->placeholder('Todas'),
                Tables\Filters\Filter::make('busqueda')
                    ->label('Búsqueda')
                    ->form([
                        Forms\Components\TextInput::make('order_number')
                            ->label('Número de orden')
                            ->numeric(),
                        Forms\Components\TextInput::make('customer_email')
                            ->label('Correo del cliente')
                            ->email(),
                        Forms\Components\TextInput::make('store')
                            ->label('Tienda (texto)'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['order_number'] ?? null, fn (Builder $q, $value) => $q->where('id_order', (int) $value))
                            ->when($data['customer_email'] ?? null, fn (Builder $q, $value) => $q->where('customer_email', 'like', "%{$value}%"))
                            ->when($data['store'] ?? null, fn (Builder $q, $value) => $q->where('store_name', 'like', "%{$value}%"));
                    }),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make()
                        ->visible(fn (Order $record): bool => ! $record->isTerminalState()),

                    Tables\Actions\Action::make('marketplace_received')
                        ->label('Marketplace: recibido en tienda')
                        ->icon('heroicon-o-inbox-arrow-down')
                        ->visible(fn (Order $record) => ! $record->isTerminalState() && $record->statusCatalog?->code === OrderStatus::OnHold->value)
                        ->requiresConfirmation()
                        ->action(function (Order $record): void {
                            /** @var ?OrderStatusCatalog $status */
                            $status = OrderStatusCatalog::query()->where('code', OrderStatus::Ingresado->value)->first();
                            if (! $status) {
                                Notification::make()->title('No existe el estado "Ingresado" en el catálogo')->danger()->send();
                                return;
                            }

                            $record->forceFill(['status_id' => $status->id_order_status])->save();
                            $record->statusLogs()->create([
                                'status' => $status->code,
                                'note' => 'Marketplace: producto recibido en tienda.',
                                'happened_at' => now(),
                            ]);

                            Notification::make()->title('Orden movida a "Ingresado"')->success()->send();
                        }),

                    Tables\Actions\Action::make('marketplace_new_order')
                        ->label('Marketplace: nueva orden (modificar productos)')
                        ->icon('heroicon-o-document-duplicate')
                        ->visible(fn (Order $record) => ! $record->isTerminalState() && $record->statusCatalog?->code === OrderStatus::OnHold->value)
                        ->requiresConfirmation()
                        ->action(function (Order $record): void {
                            if (! (auth()->user()?->can('orders.update') ?? false)) {
                                Notification::make()->title('Acción bloqueada: sin permisos')->danger()->send();
                                return;
                            }

                            $dispatchTypeId = OrderTypeCatalog::query()
                                ->where('code', OrderType::Dispatch->value)
                                ->value('id_order_type');

                            $ingresadoId = OrderStatusCatalog::query()
                                ->where('code', OrderStatus::Ingresado->value)
                                ->value('id_order_status');

                            if (! $dispatchTypeId || ! $ingresadoId) {
                                Notification::make()->title('Catálogos incompletos (tipo/estado)')->danger()->send();
                                return;
                            }

                            $newRef = Str::upper(Str::random(9));
                            for ($i = 0; $i < 10 && Order::query()->where('order_reference', $newRef)->exists(); $i++) {
                                $newRef = Str::upper(Str::random(9));
                            }

                            $record->loadMissing('details');

                            $newOrder = Order::query()->create([
                                'order_reference' => $newRef,
                                'original_order_reference' => $record->order_reference,
                                'store_id' => $record->store_id,
                                'store_name' => $record->store_name,
                                'channel_id' => $record->channel_id,
                                'order_type_id' => $dispatchTypeId,
                                'status_id' => $ingresadoId,
                                'carrier_id' => $record->carrier_id,
                                'guide' => null,
                                'codClient' => $record->codClient,
                                'customer_name' => $record->customer_name,
                                'customer_identification' => $record->customer_identification,
                                'customer_email' => $record->customer_email,
                                'customer_phone' => $record->customer_phone,
                                'customer_legal_activity' => $record->customer_legal_activity,
                                'customer_total_orders' => $record->customer_total_orders,
                                'payment' => $record->payment,
                                'total_productsTI' => $record->total_productsTI,
                                'total_productsTE' => $record->total_productsTE,
                                'total_discounts' => $record->total_discounts,
                                'total_shipping' => $record->total_shipping,
                                'total_paidTI' => $record->total_paidTI,
                                'total_paidTE' => $record->total_paidTE,
                                'date_order' => now(),
                                'postal_code' => $record->postal_code,
                                'province_id' => $record->province_id,
                                'canton_id' => $record->canton_id,
                                'district_id' => $record->district_id,
                                'address_detail' => $record->address_detail,
                            ]);

                            if ($record->details->isNotEmpty()) {
                                $newOrder->details()->createMany(
                                    $record->details->map(fn ($d) => [
                                        'order_reference' => $newRef,
                                        'product_reference' => $d->product_reference,
                                        'product_name' => $d->product_name,
                                        'product_quantity' => $d->product_quantity,
                                        'product_tax' => $d->product_tax,
                                        'product_priceTI' => $d->product_priceTI,
                                        'product_priceTE' => $d->product_priceTE,
                                        'total_priceTI' => $d->total_priceTI,
                                        'total_priceTE' => $d->total_priceTE,
                                        'warehouse_assigned' => $d->warehouse_assigned,
                                    ])->all()
                                );
                            }

                            $newOrder->statusLogs()->create([
                                'status' => OrderStatus::Ingresado->value,
                                'note' => 'Creada desde Marketplace (modificación de productos).',
                                'happened_at' => now(),
                            ]);

                            $editUrl = static::getUrl('edit', ['record' => $newOrder]);

                            Notification::make()
                                ->title('Nueva orden creada')
                                ->success()
                                ->actions([
                                    NotificationAction::make('edit')
                                        ->label('Editar productos')
                                        ->url($editUrl),
                                ])
                                ->send();
                        }),

                    Tables\Actions\Action::make('purchase_details')
                        ->label('Ver detalle de compra')
                        ->icon('heroicon-o-shopping-cart')
                        ->modalHeading('Detalle de compra')
                        ->modalContent(fn (Order $record) => view('filament.orders.modals.purchase-details', [
                            'record' => $record->loadMissing('details'),
                        ])),
                    Tables\Actions\Action::make('customer_details')
                        ->label('Ver datos del cliente')
                        ->icon('heroicon-o-user')
                        ->modalHeading('Datos del cliente')
                        ->modalContent(fn (Order $record) => view('filament.orders.modals.customer-details', [
                            'record' => $record,
                        ])),
                    Tables\Actions\Action::make('address_details')
                        ->label('Ver dirección')
                        ->icon('heroicon-o-map-pin')
                        ->modalHeading('Dirección')
                        ->modalContent(fn (Order $record) => view('filament.orders.modals.address-details', [
                            'record' => $record,
                        ])),
                    Tables\Actions\Action::make('status_log')
                        ->label('Ver bitácora de estados')
                        ->icon('heroicon-o-clock')
                        ->modalHeading('Bitácora de estados')
                        ->modalContent(fn (Order $record) => view('filament.orders.modals.status-log', [
                            'record' => $record->loadMissing(['statusLogs' => fn ($q) => $q->orderBy('happened_at')]),
                        ])),

                    Tables\Actions\Action::make('change_status')
                        ->label('Cambio de estado')
                        ->icon('heroicon-o-arrow-path')
                        ->disabled(fn (Order $record): bool => $record->isTerminalState() || ! (auth()->user()?->can('orders.update') ?? false))
                        ->form([
                            Forms\Components\Select::make('status_id')
                                ->label('Nuevo estado')
                                ->relationship(
                                    name: 'statusCatalog',
                                    titleAttribute: 'name',
                                    modifyQueryUsing: fn (Builder $query): Builder => $query
                                        ->active()
                                        ->visibleInStatusSelectors()
                                        ->orderBy('name'),
                                )
                                ->searchable()
                                ->preload()
                                ->required(),
                            Forms\Components\Textarea::make('note')
                                ->label('Nota')
                                ->rows(2),
                        ])
                        ->action(function (array $data, Order $record): void {
                            if (! (auth()->user()?->can('orders.update') ?? false)) {
                                Notification::make()->title('Acción bloqueada: sin permisos')->danger()->send();

                                return;
                            }

                            /** @var ?OrderStatusCatalog $status */
                            $status = OrderStatusCatalog::query()->find($data['status_id']);
                            if (! $status) {
                                Notification::make()->title('Estado inválido')->danger()->send();

                                return;
                            }

                            $record->forceFill(['status_id' => $status->id_order_status])->save();
                            $record->statusLogs()->create([
                                'status' => $status->code,
                                'note' => $data['note'] ?? null,
                                'happened_at' => now(),
                            ]);

                            if ($status->code === OrderStatus::ListoParaEnviar->value) {
                                try {
                                    $record->loadMissing('statusCatalog');
                                    app(ShippingService::class)->ensureShipmentCreated($record);
                                } catch (\Throwable $e) {
                                    $record->statusLogs()->create([
                                        'status' => OrderStatus::ListoParaEnviar->value,
                                        'note' => 'Fallo integración de guía: '.$e->getMessage(),
                                        'happened_at' => now(),
                                    ]);
                                }

                                if (filled($record->customer_email)) {
                                    Mail::to($record->customer_email)->send(new OrderStatusMail($record));
                                }
                            }

                            if ($status->code === OrderStatus::ListoParaRetirar->value && filled($record->customer_email)) {
                                Mail::to($record->customer_email)->send(new OrderStatusMail($record));
                            }

                            Notification::make()->title('Estado actualizado')->success()->send();
                        }),

                    Tables\Actions\Action::make('change_carrier')
                        ->label('Cambio de carrier')
                        ->icon('heroicon-o-truck')
                        ->disabled(fn (Order $record): bool => $record->isTerminalState() || ! (auth()->user()?->can('orders.update') ?? false))
                        ->form([
                            Forms\Components\Select::make('carrier_id')
                                ->label('Carrier')
                                ->relationship('carrierCatalog', 'name')
                                ->searchable()
                                ->preload()
                                ->required(),
                        ])
                        ->action(function (array $data, Order $record): void {
                            if (! (auth()->user()?->can('orders.update') ?? false)) {
                                Notification::make()->title('Acción bloqueada: sin permisos')->danger()->send();

                                return;
                            }

                            /** @var ?OrderCarrierCatalog $carrier */
                            $carrier = OrderCarrierCatalog::query()->find($data['carrier_id']);
                            if (! $carrier) {
                                Notification::make()->title('Carrier inválido')->danger()->send();

                                return;
                            }

                            $record->forceFill(['carrier_id' => $carrier->id_order_carrier])->save();

                            Notification::make()->title('Carrier actualizado')->success()->send();
                        }),

                    Tables\Actions\Action::make('resend_email')
                        ->label('Reenvío de correo')
                        ->icon('heroicon-o-paper-airplane')
                        ->disabled(fn (Order $record): bool => $record->isTerminalState() || ! (auth()->user()?->can('orders.update') ?? false))
                        ->action(function (Order $record): void {
                            if (! (auth()->user()?->can('orders.update') ?? false)) {
                                Notification::make()->title('Acción bloqueada: sin permisos')->danger()->send();

                                return;
                            }

                            if (blank($record->customer_email)) {
                                Notification::make()->title('La orden no tiene correo de cliente')->danger()->send();

                                return;
                            }

                            Mail::to($record->customer_email)->send(new OrderStatusMail($record));

                            Notification::make()->title('Correo reenviado (MAIL_MAILER=log)')->success()->send();
                        }),
                ])->label('Acciones'),
            ])
            ->bulkActions([]);
    }


    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    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'),
        ];
    }
}
