<?php

namespace App\Filament\Resources;

use App\Enums\BookingItemStatus;
use App\Enums\CommercialRegisterType;
use App\Enums\PaymentStatus;
use App\Filament\Resources\BookingItemResource;
use App\Filament\Resources\ServiceProviderResource\Pages;
use App\Filament\Resources\ServiceProviderResource\RelationManagers;
use App\Models\ServiceProvider;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class ServiceProviderResource extends Resource
{
    protected static ?int $navigationSort = 2;
    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }
    public static function getNavigationGroup(): ?string
    {
        return __('User Management');
    }
    protected static ?string $model = ServiceProvider::class;

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

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label(__('Name'))
                    ->required()
                    ->disabledOn('edit')
                    ->maxLength(255),
                Forms\Components\TextInput::make('email')
                    ->label(__('Email'))
                    ->disabledOn('edit')
                    ->email()
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('phone')
                    ->label(__('Phone'))
                    ->tel()
                    ->disabledOn('edit')
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('password')
                    ->label(__('Password'))
                    ->password()
                    ->disabledOn('edit')
                    ->required()
                    ->hiddenOn('edit'),
                Forms\Components\FileUpload::make('logo')
                    ->label(__('Logo'))
                    ->disabledOn('edit')
                    ->image()
                    ->directory('logos'),
                Forms\Components\Select::make('category_id')
                    ->label(__('Category'))
                    ->relationship('category', 'name_' . app()->getLocale())
                    ->disabledOn('edit')
                    ->preload()
                    ->required(),

                Forms\Components\Select::make('nationality_id')
                    ->label(__('Nationality'))
                    ->relationship('nationality', 'name_' . app()->getLocale())
                    ->preload()
                    ->disabledOn('edit')
                    ->required(),
                Forms\Components\TextInput::make('id_number')
                    ->label(__('ID Number'))
                    ->disabledOn('edit')
                    ->maxLength(255),
                Forms\Components\Select::make('commercial_register_type')
                    ->disabledOn('edit')
                    ->label(__('Commercial Register Type'))
                    ->options(CommercialRegisterType::options()),
                Forms\Components\TextInput::make('commercial_register_number')
                    ->label(__('Commercial Register Number'))
                    ->disabledOn('edit')
                    ->maxLength(255),
                Forms\Components\TextInput::make('iban')
                    ->label(__('IBAN'))
                    ->disabledOn('edit')
                    ->maxLength(255),
                Forms\Components\TextInput::make('bank_name')
                    ->disabledOn('edit')
                    ->label(__('Bank Name'))
                    ->maxLength(255),

                Forms\Components\Select::make('cities')
                    ->label(__('Cities'))
                    ->disabledOn('edit')
                    ->multiple()
                    ->relationship('cities', 'name_' . app()->getLocale())
                    ->preload(),
                Forms\Components\TextInput::make('commission_rate')
                    ->label(__('Commission Rate'))
                    ->minValue(0)
                    ->maxValue(100)
                    ->postfix('%')
                    ->required()
                    ->numeric(),
                Forms\Components\FileUpload::make('badge_url')
                    ->label(__('Badge URL')),

                Forms\Components\Toggle::make('is_active')
                    ->label(__('Is Active'))
                    ->default(true)
                    ->columnSpanFull()
                    ->required(),

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label(__('ID'))
                    ->sortable(),
                Tables\Columns\ImageColumn::make('logo')->label(__('Logo'))
                    ->alignCenter()
                    ->size("3rem")
                    ->circular(),
                Tables\Columns\TextColumn::make('name')->label(__('Name'))->searchable(),
                Tables\Columns\IconColumn::make('is_new')
                    ->label(__('New Provider'))
                    ->boolean()
                    ->getStateUsing(function ($record) {
                        return is_null($record->commission_rate) && !$record->is_active;
                    }),
                Tables\Columns\TextColumn::make('email')->label(__('Email'))->searchable(),
                Tables\Columns\TextColumn::make('phone')->label(__('Phone'))->searchable(),
                Tables\Columns\TextColumn::make('nationality.name_' . app()->getLocale())->label(__('Nationality'))->sortable(),
                Tables\Columns\IconColumn::make('is_active')
                    ->label(__('Is Active'))
                    ->sortable()
                    ->boolean(),
                Tables\Columns\TextColumn::make('unpaid_completed_amount')
                    ->label(__('Unpaid Amount'))
                    ->money('SAR')
                    ->url(fn($record) => BookingItemResource::getUrl('index', ['tableFilters[service_provider_id][values][0]' => $record->id, 'tableFilters[status][values]' => [BookingItemStatus::COMPLETED->value], 'tableFilters[payment_status][value]' => PaymentStatus::PAID->value, 'tableFilters[is_transfered][value]' => false]))
                    ->openUrlInNewTab(),
                Tables\Columns\TextColumn::make('completed_amount')
                    ->label(__('Completed Amount'))
                    ->money('SAR')
                    ->url(fn($record) => BookingItemResource::getUrl('index', ['tableFilters[service_provider_id][values][0]' => $record->id, 'tableFilters[status][values]' => [BookingItemStatus::COMPLETED->value], 'tableFilters[payment_status][value]' => PaymentStatus::PAID->value]))
                    ->openUrlInNewTab(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('Created At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label(__('Updated At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                \Filament\Tables\Filters\TernaryFilter::make('has_unpaid_amount')
                    ->label(__('Has Unpaid Amount'))
                    ->boolean()
                    ->trueLabel(__('Has Unpaid Amount'))
                    ->falseLabel(__('No Unpaid Amount'))
                    ->queries(
                        true: fn(Builder $query) => $query->whereHas('completedBookingItems', fn(Builder $query) => $query->where('is_transfered', false)),
                        false: fn(Builder $query) => $query->whereDoesntHave('completedBookingItems', fn(Builder $query) => $query->where('is_transfered', false)),
                        blank: fn(Builder $query) => $query,
                    ),
                \Filament\Tables\Filters\TernaryFilter::make('is_new')
                    ->label(__('New Provider'))
                    ->boolean()
                    ->trueLabel(__('New Provider'))
                    ->falseLabel(__('Old Provider'))
                    ->queries(
                        true: fn(Builder $query) => $query->whereNull('commission_rate')->where('is_active', false),
                        false: fn(Builder $query) => $query->whereNotNull('commission_rate')->orWhere('is_active', true),
                        blank: fn(Builder $query) => $query,
                    ),
                \Filament\Tables\Filters\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\EditAction::make()
                    ->visible(fn($record) => !$record->trashed()),
                Tables\Actions\DeleteAction::make()
                    ->before(function (Tables\Actions\DeleteAction $action, ServiceProvider $record) {
                        $record->load('upcomingBookingItems');
                        if ($record->upcomingBookingItems->isNotEmpty()) {
                            $lastBookingDate = $record->upcomingBookingItems->max('service_date');
                            Notification::make()
                                ->title(__('Provider Deletion Failed'))
                                ->body(__(':name could not be deleted. They have :count upcoming bookings, with the last one on :date.', [
                                    'name' => $record->name,
                                    'count' => $record->upcomingBookingItems->count(),
                                    'date' => $lastBookingDate,
                                ]))
                                ->danger()
                                ->send();
                            $action->cancel();
                        }
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->before(function (Tables\Actions\DeleteBulkAction $action, \Illuminate\Database\Eloquent\Collection $records) {
                            $records->load('upcomingBookingItems');
                            $problematicRecords = $records->filter(fn($record) => $record->upcomingBookingItems->isNotEmpty());

                            if ($problematicRecords->isNotEmpty()) {
                                $names = $problematicRecords->pluck('name')->join(', ');
                                Notification::make()
                                    ->title(__('Provider Deletion Failed'))
                                    ->body(__(':names could not be deleted because they have upcoming bookings.', ['names' => $names]))
                                    ->danger()
                                    ->send();
                                $action->cancel();
                            }
                        }),
                ]),
            ]);
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with('completedBookingItems')
            ->withTrashed()
            ->orderByRaw('(commission_rate IS NULL AND is_active = false) DESC, created_at DESC');
    }
}
