<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ServiceResource\Pages;
use App\Filament\Resources\ServiceResource\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 ServiceResource extends Resource
{

    protected static ?int $navigationSort = 2;

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::query()->where('type', 'service')->count();
    }
    public static function getNavigationGroup(): ?string
    {
        return __('Content Management');
    }

    protected static ?string $model = Product::class;

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

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

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

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


    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)') : ''))
                    ->required(),
                Forms\Components\Select::make('category_id')
                    ->label(__('Category'))
                    ->relationship('category', 'name_' . app()->getLocale())
                    ->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\TextInput::make('description_en')
                    ->label(__('Description (English)'))
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('description_ar')
                    ->label(__('Description (Arabic)'))
                    ->required()
                    ->maxLength(255),
                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(__('City'))
                    ->relationship('cities', 'name_' . app()->getLocale())
                    ->preload()
                    ->required(),
                SpatieMediaLibraryFileUpload::make('media')
                    ->label(__('Media'))
                    ->columnSpanFull()
                    ->multiple()
                    ->collection('*'),
                // SpatieMediaLibraryFileUpload::make('media')
                //     ->label(__('Videos'))
                //     ->columnSpanFull()
                //     ->multiple()
                //     ->collection('videos')
                //     ->acceptedFileTypes(['video/*']),
                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'))->searchable()->sortable(),
                Tables\Columns\TextColumn::make('name_' . app()->getLocale())->label(__('Name'))->searchable()->sortable(),
                Tables\Columns\TextColumn::make('serviceProvider.name')
                    ->label(__('Service Provider'))
                    ->url(fn($record) => ServiceProviderResource::getUrl('edit', ['record' => $record?->service_provider_id]))
                    ->searchable()->sortable()
                    ->suffix(fn($record) => $record->serviceProvider?->deleted_at ? __(' (Deleted)') : ''),
                Tables\Columns\TextColumn::make('category.name_' . app()->getLocale())
                    ->label(__('Category'))
                    ->sortable(),
                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_category', $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_category') && $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_category') && $get('has_active_city')) {
                                    $set('available', true);
                                }
                            }),
                        Forms\Components\Checkbox::make('has_active_category')
                            ->label(__('Has Active Category'))
                            ->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_category') && $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_category') && $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_category'] ?? null,
                                fn(Builder $query): Builder => $query->hasActiveCategory()
                            )
                            ->when(
                                $data['has_active_city'] ?? null,
                                fn(Builder $query): Builder => $query->hasActiveCity()
                            );
                    }),
                SelectFilter::make('category_id')
                    ->label(__('Category'))
                    ->relationship('category', 'name_' . app()->getLocale())
                    ->multiple()
                    ->searchable()
                    ->preload(),
                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(),
            ])
            ->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\ListServices::route('/'),
            'view' => Pages\ViewService::route('/{record}'),
            // 'create' => Pages\CreateService::route('/create'),
            // 'edit' => Pages\EditService::route('/{record}/edit'),
        ];
    }
}
