<?php

namespace App\Filament\Resources;

use App\Filament\Resources\OrderResource\Pages;
use App\Filament\Resources\OrderResource\RelationManagers;
use App\Models\Order;
use App\Models\PaymentMethod;
use App\Models\User;
use Filament\Actions;
use Filament\Forms;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;

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

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        return parent::getEloquentQuery()->with(['user', 'paymentMethod', 'items.variant.product', 'shippingAddress', 'purchaseOrders.supplier']);
    }

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-shopping-cart';

    protected static string | \UnitEnum | null $navigationGroup = 'إدارة الطلبات';

    protected static ?string $modelLabel = 'طلب';

    protected static ?string $pluralModelLabel = 'الطلبات';

    protected static ?int $navigationSort = 3;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('بيانات الطلب')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('التاجر')
                            ->options(User::where('is_admin', false)->pluck('name', 'id'))
                            ->searchable()
                            ->required()
                            ->disabled(fn (string $operation) => $operation === 'edit'),

                        Forms\Components\Select::make('status')
                            ->label('الحالة')
                            ->options(Order::getStatusLabels())
                            ->required()
                            ->native(false),

                        Forms\Components\Select::make('payment_method_id')
                            ->label('طريقة الدفع')
                            ->options(PaymentMethod::where('status', 'active')->orderBy('sort_order')->pluck('name', 'id'))
                            ->searchable()
                            ->native(false)
                            ->placeholder('—'),

                        Forms\Components\Placeholder::make('payment_status_badge')
                            ->label('حالة الدفع')
                            ->content(fn (Order $record) => $record->payment_status ? (Order::getPaymentStatusLabels()[$record->payment_status] ?? $record->payment_status) : '—')
                            ->visibleOn('edit'),

                        Forms\Components\Textarea::make('notes')
                            ->label('ملاحظات')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Section::make('الحسابات')
                    ->schema([
                        Forms\Components\TextInput::make('subtotal')
                            ->label('المجموع الفرعي (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('discount_from_points')
                            ->label('خصم النقاط (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('shipping_cost')
                            ->label('تكلفة الشحن (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('payment_fee')
                            ->label('رسوم الدفع (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('extra_charges')
                            ->label('مصروفات إضافية (ج.م)')
                            ->helperText('مثل: تغليف، عتالة — يتحدّث الإجمالي تلقائياً')
                            ->numeric()
                            ->minValue(0)
                            ->prefix('ج.م')
                            ->default(0),

                        Forms\Components\TextInput::make('total')
                            ->label('الإجمالي (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('total_profit')
                            ->label('إجمالي الربح (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('points_earned')
                            ->label('النقاط المكتسبة')
                            ->numeric()
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\TextInput::make('points_redeemed')
                            ->label('النقاط المستبدلة')
                            ->numeric()
                            ->disabled()
                            ->dehydrated(false),
                    ])
                    ->columns(3)
                    ->visibleOn('edit'),

                Section::make('عنوان الشحن')
                    ->schema([
                        Forms\Components\TextInput::make('shipping_governorate')
                            ->label('المحافظة')
                            ->disabled()
                            ->dehydrated(false),

                        Forms\Components\Textarea::make('shipping_address_snapshot')
                            ->label('العنوان الكامل')
                            ->disabled()
                            ->dehydrated(false)
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->visibleOn('edit'),

                Section::make('إيصال الدفع')
                    ->description('صورة الإيصال المرفوعة من التاجر (للطرق الإلكترونية والتحويل)')
                    ->schema([
                        Forms\Components\ViewField::make('payment_receipt')
                            ->view('filament.forms.components.payment-receipt-display')
                            ->viewData(fn ($get) => ['receiptPath' => $get('payment_receipt')]),
                    ])
                    ->visible(fn (Order $record) => $record && $record->payment_receipt)
                    ->visibleOn('edit'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('رقم الطلب')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('user.name')
                    ->label('التاجر')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('status')
                    ->label('الحالة')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => Order::getStatusLabels()[$state] ?? $state)
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'gray',
                        'pending_supplier' => 'warning',
                        'ordered_from_supplier' => 'info',
                        'received_from_supplier' => 'info',
                        'processing' => 'primary',
                        'shipping' => 'warning',
                        'delivered' => 'success',
                        'returned' => 'danger',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('paymentMethod.name')
                    ->label('طريقة الدفع')
                    ->placeholder(fn (Order $r) => $r->payment_method ?: '—'),

                Tables\Columns\TextColumn::make('payment_status')
                    ->label('حالة الدفع')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => $state ? (Order::getPaymentStatusLabels()[$state] ?? $state) : '—')
                    ->color(fn (?string $state): string => match ($state) {
                        'confirmed' => 'success',
                        'rejected' => 'danger',
                        'pending' => 'warning',
                        default => 'gray',
                    })
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('shipping_cost')
                    ->label('الشحن')
                    ->money('EGP')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('payment_fee')
                    ->label('رسوم الدفع')
                    ->money('EGP')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('total')
                    ->label('الإجمالي (ج.م)')
                    ->money('EGP')
                    ->sortable(),

                Tables\Columns\TextColumn::make('total_profit')
                    ->label('الربح (ج.م)')
                    ->money('EGP')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('items_count')
                    ->label('الأصناف')
                    ->counts('items'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('التاريخ')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->defaultSort('id', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('الحالة')
                    ->options(Order::getStatusLabels())
                    ->multiple(),
            ])
            ->actions([
                Actions\Action::make('print_invoice')
                    ->label('فاتورة')
                    ->icon('heroicon-o-document-text')
                    ->url(fn (Order $record) => route('admin.orders.invoice-pdf', ['order' => $record->id]))
                    ->openUrlInNewTab(),
                Actions\Action::make('print_waybill')
                    ->label('بوليصة')
                    ->icon('heroicon-o-truck')
                    ->url(fn (Order $record) => route('admin.orders.waybill-pdf', ['order' => $record->id]))
                    ->openUrlInNewTab(),
                Actions\EditAction::make()->label('تعديل'),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\DeleteBulkAction::make()->label('حذف المحدد'),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\ItemsRelationManager::class,
            RelationManagers\PurchaseOrdersRelationManager::class,
        ];
    }

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