<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpCustomers;

use App\Business\MasterData\Enums\SettlementMethod;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpRegionAddress;
use App\Filament\Resources\DberpCustomers\Concerns\ProvidesDberpCustomerBusinessOverviewFormSections;
use App\Filament\Resources\DberpCustomers\Pages\CreateDberpCustomer;
use App\Filament\Resources\DberpCustomers\Pages\EditDberpCustomer;
use App\Filament\Resources\DberpCustomers\Pages\ListDberpCustomers;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpCustomer;
use App\Models\DberpCustomerCategory;
use App\Models\DberpSalesperson;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpPriceLevelDictionary;
use BackedEnum;
use Closure;
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 DberpCustomerResource extends Resource
{
    use HasDberpRegionAddress;
    use InteractsWithDberpPermissions;
    use ProvidesDberpCustomerBusinessOverviewFormSections;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 20;

    protected static bool $isGloballySearchable = true;

    protected static ?int $globalSearchSort = 20;

    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 DberpCustomer) {
            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::customerBusinessOverviewFormSections(),
                Section::make(__('dberp.sections.master_basic'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.customer_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.customer_name'))
                            ->required()
                            ->maxLength(160),
                        Select::make('customer_category_id')
                            ->label(__('dberp.fields.customer_category'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpCustomer) {
                                    $preserve = $livewire->getRecord()->customer_category_id;
                                }

                                return DberpCustomerCategory::optionsForCustomerMasterForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->preload()
                            ->nullable(),
                        Select::make('settlement_method')
                            ->label(__('dberp.fields.settlement_method'))
                            ->options(SettlementMethod::options())
                            ->default(SettlementMethod::Cash->value)
                            ->required(),
                        Select::make('salesperson_employee_id')
                            ->label(__('dberp.fields.salesperson_employee'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpCustomer) {
                                    $preserve = $livewire->getRecord()->salesperson_employee_id;
                                }

                                return DberpSalesperson::optionsForCustomerMasterForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->searchable()
                            ->preload()
                            ->helperText(__('dberp.hints.customer_salesperson_from_profiles'))
                            ->nullable(),
                        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(),
                Section::make(__('dberp.sections.sales_credit_control'))
                    ->schema([
                        Select::make('price_level_code')
                            ->label(__('dberp.fields.price_level_code'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpCustomer) {
                                    $preserve = $livewire->getRecord()->price_level_code;
                                }

                                return DberpPriceLevelDictionary::optionsForSelect(
                                    is_string($preserve) && $preserve !== '' ? $preserve : null,
                                );
                            })
                            ->searchable()
                            ->preload()
                            ->nullable()
                            ->helperText(__('dberp.hints.customer_price_level_code'))
                            ->rules([
                                fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
                                    if ($value === null || $value === '') {
                                        return;
                                    }

                                    if (! DberpPriceLevelDictionary::isEnabledCode((string) $value)) {
                                        $fail((string) __('dberp.errors.price_level_code_invalid'));
                                    }
                                },
                            ]),
                        TextInput::make('default_payment_term_days')
                            ->label(__('dberp.fields.default_payment_term_days'))
                            ->numeric()
                            ->minValue(0),
                        DberpFilamentNumberFields::moneyInput(
                            TextInput::make('credit_limit_amount')
                                ->label(__('dberp.fields.credit_limit_amount')),
                            withHelperText: false,
                            minValue: 0.0,
                        ),
                        Textarea::make('credit_control_note')
                            ->label(__('dberp.fields.credit_control_note'))
                            ->rows(2)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.customer_code'))
                    ->searchable(),
                TextColumn::make('name')
                    ->label(__('dberp.fields.customer_name'))
                    ->searchable(),
                TextColumn::make('customerCategory.name')
                    ->label(__('dberp.fields.customer_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),
                TextColumn::make('price_level_code')
                    ->label(__('dberp.fields.price_level_code'))
                    ->formatStateUsing(fn (?string $state): string => $state === null || $state === ''
                        ? '-'
                        : DberpPriceLevelDictionary::displayLabel($state))
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('default_payment_term_days')
                    ->label(__('dberp.fields.default_payment_term_days'))
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('credit_limit_amount')
                    ->label(__('dberp.fields.credit_limit_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('salesperson_employee_id')
                    ->label(__('dberp.fields.salesperson_employee'))
                    ->formatStateUsing(function ($state, DberpCustomer $record): string {
                        if ($state === null || $state === '') {
                            return '-';
                        }

                        $profile = $record->latestSalespersonProfile;
                        if ($profile !== null) {
                            return $profile->labelForSelectWithOrganization();
                        }

                        return $record->salesperson !== null
                            ? $record->salesperson->labelForSelectWithOrganization()
                            : '-';
                    }),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('customer_category_id')
                    ->label(__('dberp.fields.customer_category'))
                    ->relationship('customerCategory', '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_CUSTOMER);
    }

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

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

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

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with([
            'salesperson.department',
            'salesperson.position',
            'latestSalespersonProfile.employee.department',
            'latestSalespersonProfile.employee.position',
            'latestSalespersonProfile.department',
            'latestSalespersonProfile.position',
            'region',
            'customerCategory',
        ]);
    }

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