<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\DberpSupplierCategories;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpSupplierCategories\Pages\CreateDberpSupplierCategory;
use App\Filament\Resources\DberpSupplierCategories\Pages\EditDberpSupplierCategory;
use App\Filament\Resources\DberpSupplierCategories\Pages\ListDberpSupplierCategories;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\DberpSupplierCategory;
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 DberpSupplierCategoryResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 31;

    /**
     * @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.supplier_category_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.supplier_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.supplier_category_status');
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpSupplierCategory) {
                                    /** @var DberpSupplierCategory $category */
                                    $category = $livewire->getRecord();
                                    if ($category->suppliers()->exists()) {
                                        return $base.' '.(string) __('dberp.hints.supplier_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.supplier_category_code'))
                    ->tooltip(__('dberp.hints.supplier_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.supplier_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 (DberpSupplierCategory $record): bool => (int) $record->suppliers_count === 0),
            ]);
    }

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

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_MASTER_SUPPLIER_CATEGORY,
            DberpPermissionService::CREATE_MASTER_SUPPLIER_CATEGORY,
            DberpPermissionService::EDIT_MASTER_SUPPLIER_CATEGORY,
            DberpPermissionService::DELETE_MASTER_SUPPLIER_CATEGORY,
        ]);
    }

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

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpSupplierCategories::route('/'),
            'create' => CreateDberpSupplierCategory::route('/create'),
            'edit' => EditDberpSupplierCategory::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.supplier_category.label');
    }

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