<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpCustomerCategories;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpCustomerCategories\Pages\CreateDberpCustomerCategory;
use App\Filament\Resources\DberpCustomerCategories\Pages\EditDberpCustomerCategory;
use App\Filament\Resources\DberpCustomerCategories\Pages\ListDberpCustomerCategories;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\DberpCustomerCategory;
use App\Services\DberpPermissionService;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpCustomerCategoryResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 21;

    /**
     * @return array<string, string>
     */
    private static function masterRecordStatusOptions(): array
    {
        $raw = __('dberp.options.master_record_status');

        return is_array($raw) ? $raw : [];
    }

    public static function form(Schema $schema): Schema
    {
        $statusOptions = static::masterRecordStatusOptions();

        return $schema
            ->components([
                Section::make(__('dberp.sections.master_basic'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.customer_category_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.customer_category_name'))
                            ->required()
                            ->maxLength(120),
                        Select::make('status')
                            ->label(__('dberp.fields.status'))
                            ->options($statusOptions)
                            ->default('active')
                            ->required()
                            ->helperText(function ($livewire): string {
                                $base = (string) __('dberp.hints.customer_category_status');
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpCustomerCategory) {
                                    /** @var DberpCustomerCategory $category */
                                    $category = $livewire->getRecord();
                                    if ($category->customers()->exists()) {
                                        return $base.' '.(string) __('dberp.hints.customer_category_prefer_disable_when_used');
                                    }
                                }

                                return $base;
                            }),
                        TextInput::make('sort')
                            ->label(__('dberp.fields.sort'))
                            ->numeric()
                            ->default(0)
                            ->required(),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        $statusOptions = static::masterRecordStatusOptions();

        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->orderBy('sort')->orderByDesc('id'))
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.customer_category_code'))
                    ->tooltip(__('dberp.hints.customer_category_table_search'))
                    ->searchable(query: function (Builder $query, string $search): Builder {
                        $like = '%'.$search.'%';

                        return $query->where(function (Builder $inner) use ($like): void {
                            $inner->where($inner->qualifyColumn('code'), 'like', $like)
                                ->orWhere($inner->qualifyColumn('name'), 'like', $like);
                        });
                    }),
                TextColumn::make('name')
                    ->label(__('dberp.fields.customer_category_name')),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(function (?string $state) use ($statusOptions): string {
                        $key = (string) $state;

                        return is_string($statusOptions[$key] ?? null) ? $statusOptions[$key] : $key;
                    }),
                TextColumn::make('sort')
                    ->label(__('dberp.fields.sort'))
                    ->sortable(),
                TextColumn::make('created_at')
                    ->label(__('dberp.fields.created_at'))
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options($statusOptions),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make()
                    ->visible(fn (DberpCustomerCategory $record): bool => (int) $record->customers_count === 0),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->withCount('customers');
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_MASTER_CUSTOMER_CATEGORY,
            DberpPermissionService::CREATE_MASTER_CUSTOMER_CATEGORY,
            DberpPermissionService::EDIT_MASTER_CUSTOMER_CATEGORY,
            DberpPermissionService::DELETE_MASTER_CUSTOMER_CATEGORY,
        ]);
    }

    public static function canView(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canCreate(): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_MASTER_CUSTOMER_CATEGORY);
    }

    public static function canEdit(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_MASTER_CUSTOMER_CATEGORY);
    }

    public static function canDelete(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::DELETE_MASTER_CUSTOMER_CATEGORY);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpCustomerCategories::route('/'),
            'create' => CreateDberpCustomerCategory::route('/create'),
            'edit' => EditDberpCustomerCategory::route('/{record}/edit'),
        ];
    }

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.basic_data');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.customer_category.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.customer_category.plural');
    }
}
