<?php

namespace App\Filament\Resources;

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

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        return parent::getEloquentQuery()->with(['variants', 'pricingTiers', 'supplier']);
    }

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-squares-2x2';

    protected static string | \UnitEnum | null $navigationGroup = 'إدارة المنتجات';

    protected static ?string $modelLabel = 'منتج';

    protected static ?string $pluralModelLabel = 'المنتجات';

    protected static ?int $navigationSort = 2;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('بيانات المنتج')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('اسم المنتج')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\Select::make('fulfillment_type')
                            ->label('نوع التوفير')
                            ->options([
                                'in_stock' => 'من المخزون',
                                'on_demand' => 'حسب الطلب',
                            ])
                            ->required()
                            ->default('in_stock')
                            ->native(false),

                        Forms\Components\Select::make('supplier_id')
                            ->label('المورد المسئول')
                            ->options(Supplier::where('is_active', true)->where('is_company_warehouse', false)->pluck('name', 'id'))
                            ->searchable()
                            ->nullable()
                            ->helperText('مورد افتراضي للنقشات إن لم يُحدد لكل نقشة على حدة'),

                        Forms\Components\Textarea::make('description')
                            ->label('الوصف')
                            ->maxLength(1000)
                            ->columnSpanFull(),

                        Forms\Components\FileUpload::make('image')
                            ->label('صورة المنتج')
                            ->image()
                            ->directory('products')
                            ->disk('public')
                            ->imageResizeMode('cover')
                            ->imageCropAspectRatio('4:3')
                            ->imageResizeTargetWidth('800')
                            ->imageResizeTargetHeight('600')
                            ->columnSpanFull(),

                        Forms\Components\Toggle::make('is_active')
                            ->label('نشط')
                            ->default(true),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('#')
                    ->sortable(),

                Tables\Columns\ImageColumn::make('image')
                    ->label('الصورة')
                    ->disk('public')
                    ->getStateUsing(fn ($record) => $record->image_thumbnail ?? $record->image)
                    ->circular()
                    ->defaultImageUrl(fn () => 'https://ui-avatars.com/api/?name=P&background=10b981&color=fff'),

                Tables\Columns\TextColumn::make('name')
                    ->label('اسم المنتج')
                    ->searchable()
                    ->sortable()
                    ->limit(40),

                Tables\Columns\TextColumn::make('supplier.name')
                    ->label('المورد')
                    ->placeholder('—')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('fulfillment_type')
                    ->label('نوع التوفير')
                    ->badge()
                    ->formatStateUsing(fn (string $state) => match ($state) {
                        'in_stock' => 'من المخزون',
                        'on_demand' => 'حسب الطلب',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'in_stock' => 'success',
                        'on_demand' => 'warning',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('variants_count')
                    ->label('عدد النقشات')
                    ->counts('variants')
                    ->sortable(),

                Tables\Columns\TextColumn::make('variants_sum_stock')
                    ->label('إجمالي المخزون')
                    ->sum('variants', 'stock')
                    ->sortable(),

                Tables\Columns\TextColumn::make('pricing_tiers_count')
                    ->label('الشرائح')
                    ->counts('pricingTiers'),

                Tables\Columns\IconColumn::make('is_active')
                    ->label('نشط')
                    ->boolean(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاريخ الإضافة')
                    ->dateTime('d/m/Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('id', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('fulfillment_type')
                    ->label('نوع التوفير')
                    ->options([
                        'in_stock' => 'من المخزون',
                        'on_demand' => 'حسب الطلب',
                    ]),

                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('الحالة')
                    ->trueLabel('نشط')
                    ->falseLabel('غير نشط'),
            ])
            ->actions([
                Actions\EditAction::make()->label('تعديل'),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\DeleteBulkAction::make()->label('حذف المحدد'),
                ]),
            ]);
    }

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

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