<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PackageResource\Pages;
use App\Filament\Resources\PackageResource\RelationManagers;
use App\Models\Product;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class PackageResource extends Resource
{
    protected static ?int $navigationSort = 3;

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::query()->where('type', 'package')->count();
    }
    public static function getNavigationGroup(): ?string
    {
        return __('Content Management');
    }
    protected static ?string $model = Product::class;

    protected static ?string $navigationIcon = 'heroicon-o-archive-box';

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['serviceProvider' => fn($query) => $query->withTrashed()])->withAvg('reviews', 'rating')->where('type', 'package')
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }

    public static function getLabel(): ?string
    {
        return __('Package');
    }

    public static function getPluralLabel(): ?string
    {
        return __('Packages');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('service_provider_id')
                    ->label(__('Service Provider'))
                    ->relationship('serviceProvider', 'name', fn(Builder $query) => $query->withTrashed())
                    ->getOptionLabelFromRecordUsing(fn($record) => $record->name . ($record->deleted_at ? __(' (Deleted)') : ''))
                    ->columnSpanFull()
                    ->required(),
                Forms\Components\TextInput::make('name_en')
                    ->label(__('Name (English)'))
                    ->required()
                    ->maxLength(100),
                Forms\Components\TextInput::make('name_ar')
                    ->label(__('Name (Arabic)'))
                    ->required()
                    ->maxLength(100),
                Forms\Components\Textarea::make('details_en')
                    ->label(__('Details (English)'))
                    ->required(),
                Forms\Components\Textarea::make('details_ar')
                    ->label(__('Details (Arabic)'))
                    ->required(),
                Forms\Components\TextInput::make('price')
                    ->label(__('Price'))
                    ->required()
                    ->numeric()
                    ->prefix('SAR'),
                Forms\Components\TextInput::make('price_before_discount')
                    ->label(__('Price Before Discount'))
                    ->numeric()
                    ->prefix('SAR'),
                Forms\Components\TextInput::make('location_url')
                    ->label(__('Location URL'))
                    ->url()
                    ->maxLength(255),
                Forms\Components\Select::make('cities')
                    ->label(__('Cities'))
                    ->multiple()
                    ->relationship('cities', 'name_' . app()->getLocale())
                    ->preload(),
                SpatieMediaLibraryFileUpload::make('media')
                    ->label(__('Media'))
                    ->columnSpanFull()
                    ->multiple()
                    ->collection('*')
                    ->image(),
                Forms\Components\Toggle::make('is_active')
                    ->label(__('Is Active'))
                    ->required()
                    ->default(true),

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label(__('ID'))
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_' . app()->getLocale())->label(__('Name'))->searchable()->sortable(),
                Tables\Columns\TextColumn::make('serviceProvider.name')
                    ->url(fn($record) => ServiceProviderResource::getUrl('edit', ['record' => $record?->service_provider_id]))
                    ->label(__('Service Provider'))
                    ->searchable()
                    ->sortable()
                    ->suffix(fn($record) => $record->serviceProvider?->deleted_at ? __(' (Deleted)') : ''),
                Tables\Columns\TextColumn::make('cities.name_' . app()->getLocale())
                    ->label(__('Cities'))
                    ->badge(),
                Tables\Columns\TextColumn::make('price')->label(__('Price'))->money('SAR')->sortable(),
                Tables\Columns\ViewColumn::make('reviews_avg_rating')
                    ->label(__('Avg Rating'))
                    ->view('filament.tables.columns.star-rating'),
                Tables\Columns\IconColumn::make('is_active')->label(__('Is Active'))->boolean(),
            ])
            ->filters([
                Filter::make('available')
                    ->form([
                        Forms\Components\Checkbox::make('available')
                            ->label(__('Available'))
                            ->live()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('is_active', $state);
                                $set('has_active_service_provider', $state);
                                $set('has_active_city', $state);
                            }),
                        Forms\Components\Checkbox::make('is_active')
                            ->label(__('Is Active'))
                            ->live()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if (!$state) {
                                    $set('available', false);
                                }
                                if ($get('is_active') && $get('has_active_service_provider') && $get('has_active_city')) {
                                    $set('available', true);
                                }
                            }),
                        Forms\Components\Checkbox::make('has_active_service_provider')
                            ->label(__('Has Active Service Provider'))
                            ->live()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if (!$state) {
                                    $set('available', false);
                                }
                                if ($get('is_active') && $get('has_active_service_provider') && $get('has_active_city')) {
                                    $set('available', true);
                                }
                            }),
                        Forms\Components\Checkbox::make('has_active_city')
                            ->label(__('Has Active City'))
                            ->live()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if (!$state) {
                                    $set('available', false);
                                }
                                if ($get('is_active') && $get('has_active_service_provider') && $get('has_active_city')) {
                                    $set('available', true);
                                }
                            }),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['is_active'] ?? null,
                                fn(Builder $query): Builder => $query->active()
                            )
                            ->when(
                                $data['has_active_service_provider'] ?? null,
                                fn(Builder $query): Builder => $query->hasActiveServiceProvider()
                            )
                            ->when(
                                $data['has_active_city'] ?? null,
                                fn(Builder $query): Builder => $query->hasActiveCity()
                            );
                    }),
                SelectFilter::make('cities')
                    ->label(__('City'))
                    ->relationship('cities', 'name_' . app()->getLocale())
                    ->multiple()
                    ->searchable()
                    ->preload(),
                SelectFilter::make('reviews_avg_rating')
                    ->label(__('Avg Rating'))
                    ->options([
                        '4' => '4 stars & up',
                        '3' => '3 stars & up',
                        '2' => '2 stars & up',
                        '1' => '1 star & up',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query->when(
                            $data['value'],
                            fn(Builder $query, $value): Builder => $query->whereHas('reviews', null, '>=', 1, 'and', function ($query) use ($value) {
                                $query->selectRaw('avg(rating) >= ?', [$value]);
                            }),
                        );
                    }),
                SelectFilter::make('service_provider_id')
                    ->label(__('Service Provider'))
                    ->relationship('serviceProvider', 'name')
                    ->multiple()
                    ->searchable()
                    ->preload(),
                TernaryFilter::make('is_active')
                    ->label(__('Is Active')),
                // TrashedFilter::make(),
                Filter::make('created_at')
                    ->form([
                        Forms\Components\DatePicker::make('created_from')->label(__('Created From')),
                        Forms\Components\DatePicker::make('created_until')->label(__('Created To')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn(Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
                            )
                            ->when(
                                $data['created_until'],
                                fn(Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
                            );
                    }),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                // Tables\Actions\RestoreAction::make(),
                // Tables\Actions\ForceDeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    // Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPackages::route('/'),
            'view' => Pages\ViewPackage::route('/{record}'),
            // 'create' => Pages\CreatePackage::route('/create'),
            // 'edit' => Pages\EditPackage::route('/{record}/edit'),
        ];
    }
}
