<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSuppliers;

use App\Business\MasterData\Enums\SettlementMethod;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpRegionAddress;
use App\Filament\Resources\DberpSuppliers\Concerns\ProvidesDberpSupplierBusinessOverviewFormSections;
use App\Filament\Resources\DberpSuppliers\Pages\CreateDberpSupplier;
use App\Filament\Resources\DberpSuppliers\Pages\EditDberpSupplier;
use App\Filament\Resources\DberpSuppliers\Pages\ListDberpSuppliers;
use App\Models\DberpSupplier;
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\Forms\Components\Toggle;
use Filament\Resources\Pages\EditRecord;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpSupplierResource extends Resource
{
    use HasDberpRegionAddress;
    use InteractsWithDberpPermissions;
    use ProvidesDberpSupplierBusinessOverviewFormSections;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 30;

    protected static bool $isGloballySearchable = true;

    protected static ?int $globalSearchSort = 30;

    protected static int $globalSearchResultsLimit = 30;

    /**
     * @return array<int, string>
     */
    public static function getGloballySearchableAttributes(): array
    {
        return ['code', 'name', 'contact_person', 'mobile', 'phone'];
    }

    public static function getGlobalSearchEloquentQuery(): Builder
    {
        return static::getModel()::query();
    }

    /**
     * @return array<string, string>
     */
    public static function getGlobalSearchResultDetails(Model $record): array
    {
        if (! $record instanceof DberpSupplier) {
            return [];
        }

        $details = [
            (string) __('dberp.global_search.detail_code') => (string) $record->code,
        ];

        if (filled($record->contact_person)) {
            $details[(string) __('dberp.global_search.detail_contact')] = (string) $record->contact_person;
        }

        $phone = $record->mobile ?: $record->phone;
        if (filled($phone)) {
            $details[(string) __('dberp.global_search.detail_phone')] = (string) $phone;
        }

        return array_filter($details, static fn (string $v): bool => $v !== '');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                ...static::supplierBusinessOverviewFormSections(),
                Section::make(__('dberp.sections.master_basic'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.supplier_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.supplier_name'))
                            ->required()
                            ->maxLength(160),
                        Select::make('supplier_category_id')
                            ->label(__('dberp.fields.supplier_category'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpSupplier) {
                                    $preserve = $livewire->getRecord()->supplier_category_id;
                                }

                                return DberpSupplierCategory::optionsForSupplierMasterForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->preload()
                            ->nullable(),
                        Select::make('settlement_method')
                            ->label(__('dberp.fields.settlement_method'))
                            ->options(SettlementMethod::options())
                            ->default(SettlementMethod::Cash->value)
                            ->required(),
                        Toggle::make('is_enabled')
                            ->label(__('dberp.fields.is_enabled'))
                            ->default(true),
                        TextInput::make('sort_order')
                            ->label(__('dberp.fields.sort_order'))
                            ->numeric()
                            ->default(0)
                            ->required(),
                    ])
                    ->columns(2),
                Section::make(__('dberp.sections.master_contact'))
                    ->schema([
                        TextInput::make('contact_person')
                            ->label(__('dberp.fields.contact_person'))
                            ->maxLength(120),
                        TextInput::make('mobile')
                            ->label(__('dberp.fields.mobile'))
                            ->maxLength(32),
                        TextInput::make('phone')
                            ->label(__('dberp.fields.phone'))
                            ->maxLength(32),
                        TextInput::make('email')
                            ->label(__('dberp.fields.email'))
                            ->email()
                            ->maxLength(120),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
                static::getDberpRegionAddressSection(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.supplier_code'))
                    ->searchable(),
                TextColumn::make('name')
                    ->label(__('dberp.fields.supplier_name'))
                    ->searchable(),
                TextColumn::make('supplierCategory.name')
                    ->label(__('dberp.fields.supplier_category'))
                    ->placeholder('-'),
                TextColumn::make('contact_person')
                    ->label(__('dberp.fields.contact_person')),
                TextColumn::make('mobile')
                    ->label(__('dberp.fields.mobile')),
                ...static::getDberpRegionAddressTableColumns(),
                TextColumn::make('settlement_method')
                    ->label(__('dberp.fields.settlement_method'))
                    ->formatStateUsing(fn (?string $state): string => SettlementMethod::tryFrom((string) $state)?->label() ?? (string) $state),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('supplier_category_id')
                    ->label(__('dberp.fields.supplier_category'))
                    ->relationship('supplierCategory', 'name', fn (Builder $query): Builder => $query->orderBy('sort')->orderByDesc('id'))
                    ->preload(),
                ...static::getDberpRegionCountryFilters(),
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_MASTER_SUPPLIER);
    }

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

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

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

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['region', 'supplierCategory']);
    }

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