<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PurchaseOrderResource\Pages;
use App\Filament\Resources\PurchaseOrderResource\RelationManagers;
use App\Models\Order;
use App\Models\PurchaseOrder;
use App\Models\Supplier;
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 PurchaseOrderResource extends Resource
{
    protected static ?string $model = PurchaseOrder::class;

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-clipboard-document-list';

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

    protected static ?string $modelLabel = 'أمر شراء';

    protected static ?string $pluralModelLabel = 'أوامر الشراء';

    protected static ?int $navigationSort = 4;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('بيانات أمر الشراء')
                    ->schema([
                        Forms\Components\Select::make('supplier_id')
                            ->label('المورد')
                            ->options(Supplier::where('is_active', true)->pluck('name', 'id'))
                            ->searchable()
                            ->required(),

                        Forms\Components\Select::make('source_order_id')
                            ->label('الطلب المرتبط')
                            ->options(Order::pluck('id', 'id')->mapWithKeys(fn ($id) => [$id => "طلب رقم #{$id}"]))
                            ->searchable()
                            ->nullable(),

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

                        Forms\Components\TextInput::make('total_cost')
                            ->label('الإجمالي (ج.م)')
                            ->numeric()
                            ->prefix('ج.م')
                            ->default(0),

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

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

                Tables\Columns\TextColumn::make('supplier.name')
                    ->label('المورد')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('status')
                    ->label('الحالة')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => PurchaseOrder::getStatusLabels()[$state] ?? $state)
                    ->color(fn (string $state): string => match ($state) {
                        'draft' => 'gray',
                        'confirmed' => 'warning',
                        'received' => 'success',
                        default => 'gray',
                    }),

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

                Tables\Columns\TextColumn::make('sourceOrder.id')
                    ->label('طلب مرتبط')
                    ->formatStateUsing(fn ($state) => $state ? "#{$state}" : '—')
                    ->placeholder('—'),

                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(PurchaseOrder::getStatusLabels()),

                Tables\Filters\SelectFilter::make('supplier_id')
                    ->label('المورد')
                    ->options(Supplier::pluck('name', 'id'))
                    ->searchable(),
            ])
            ->actions([
                Actions\Action::make('print_preparation_slip')
                    ->label('إذن تجهيز')
                    ->icon('heroicon-o-document-text')
                    ->url(fn (PurchaseOrder $record) => route('admin.purchase-orders.preparation-slip', ['purchaseOrder' => $record->id]))
                    ->openUrlInNewTab(),
                Actions\EditAction::make()->label('تعديل'),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\DeleteBulkAction::make()->label('حذف المحدد'),
                ]),
            ]);
    }

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

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