<?php

namespace App\Filament\Resources;

use App\Filament\Resources\Concerns\HasModulePermissions;
use App\Filament\Resources\Concerns\HasStandardTableFeatures;
use App\Filament\Resources\SupplierResource\Pages\CreateSupplier;
use App\Filament\Resources\SupplierResource\Pages\EditSupplier;
use App\Filament\Resources\SupplierResource\Pages\ListSuppliers;
use App\Filament\Support\Perm;
use App\Filament\Support\RelationSelect;
use App\Filament\Support\StatusLookup;
use App\Models\Lookups\Status;
use App\Models\Purchasing\Supplier;
use App\Services\AuditLog;
use App\Services\CurrentContext;
use App\Services\SupplierService;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

/**
 * Ported from App\Http\Controllers\Isms\SupplierController
 * (docs/migration-plan.md Phase 3). contacts/addresses/bank_accounts use
 * Filament's native Repeater::relationship() — the source controller's
 * syncContacts/syncAddresses/syncBankAccounts already do an id-aware
 * update-or-create + delete-orphans diff, which is exactly what Filament's
 * relationship-repeater does natively, so no custom sync helper is needed
 * here (unlike Product's attributes, which do a
 * different delete+reinsert operation and got their own Sync helpers).
 * status_id is never directly editable — set to SUPPLIER_ACTIVE on create,
 * changed only via the blacklist/unblacklist actions (SupplierService),
 * matching the source exactly.
 */
class SupplierResource extends Resource
{
    use HasModulePermissions;
    use HasStandardTableFeatures;

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

    protected static string $permissionModuleKey = 'isms_suppliers';

    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedTruck;

    protected static string|\UnitEnum|null $navigationGroup = 'Master Data';

    protected static ?int $navigationSort = 60;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make()->schema([
                TextInput::make('name')->required()->maxLength(150)->columnSpanFull(),
                TextInput::make('business_name')->maxLength(200),
                TextInput::make('registration_number')->maxLength(80),
                TextInput::make('tax_number')->maxLength(80),
                TextInput::make('phone')
                    ->tel()
                    ->maxLength(30)
                    ->placeholder('e.g. +94 77 123 4567')
                    ->helperText('International format with country code.'),
                TextInput::make('email')->email()->maxLength(150),
                TextInput::make('website')->url()->maxLength(200),
                RelationSelect::make(
                    name: 'payment_terms_id',
                    relationship: 'paymentTerms',
                    titleAttribute: 'name',
                )->label('Payment Terms'),
                // DB column is `decimal(12,2) default 0`, NOT NULL — same
                // Eloquent-bypasses-DB-default gotcha as ProductResource::vat_rate.
                TextInput::make('credit_limit')->numeric()->minValue(0)->maxValue(99999999.99)->prefix('Rs.')->default(0),
                Textarea::make('notes')->maxLength(1000)->columnSpanFull(),
            ]),

            Section::make('Contacts')->schema([
                Repeater::make('contacts')
                    ->relationship()
                    ->schema([
                        TextInput::make('name')->required()->maxLength(100),
                        TextInput::make('designation')->maxLength(100),
                        TextInput::make('phone')
                            ->tel()
                            ->maxLength(30)
                            ->placeholder('e.g. +94 77 123 4567')
                            ->helperText('International format with country code.'),
                        TextInput::make('email')->email()->maxLength(150),
                        Toggle::make('is_primary'),
                    ])
                    ->columns(2)
                    ->defaultItems(0)
                    ->addActionLabel('Add contact')
                    ->columnSpanFull(),
            ]),

            Section::make('Addresses')->schema([
                Repeater::make('addresses')
                    ->relationship()
                    ->schema([
                        RelationSelect::make(
                            name: 'address_type_id',
                            relationship: 'addressType',
                            titleAttribute: 'name',
                        )->label('Type')->required(),
                        TextInput::make('street_line1')->label('Address line 1')->required()->maxLength(200),
                        TextInput::make('street_line2')->label('Address line 2')->maxLength(200),
                        RelationSelect::make(
                            name: 'city_id',
                            relationship: 'city',
                            titleAttribute: 'name',
                        )->label('City'),
                        Toggle::make('is_primary'),
                    ])
                    ->columns(2)
                    ->defaultItems(0)
                    ->addActionLabel('Add address')
                    ->columnSpanFull(),
            ]),

            Section::make('Bank Accounts')->schema([
                Repeater::make('bankAccounts')
                    ->relationship()
                    ->schema([
                        TextInput::make('bank_name')->required()->maxLength(100),
                        TextInput::make('branch_name')->maxLength(100),
                        TextInput::make('account_number')->required()->maxLength(50),
                        TextInput::make('account_holder')->required()->maxLength(150),
                        Toggle::make('is_primary'),
                    ])
                    ->columns(2)
                    ->defaultItems(0)
                    ->addActionLabel('Add bank account')
                    ->columnSpanFull(),
            ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return static::standardTableDefaults($table)
            ->recordUrl(static::standardRecordUrl())
            ->emptyStateHeading('No suppliers yet')
            ->emptyStateDescription('Suppliers added to the catalog will appear here.')
            ->columns([
                TextColumn::make('name')->searchable()->sortable(),
                TextColumn::make('business_name')->placeholder('—')->searchable(),
                TextColumn::make('phone')->placeholder('—'),
                TextColumn::make('outstanding_balance')->money(fn () => app(CurrentContext::class)->currencyCode())->sortable(),
                TextColumn::make('status.name')
                    ->badge()
                    ->color(fn (Supplier $record): string => StatusLookup::colorOfStatus($record->status)),
            ])
            ->filters([
                SelectFilter::make('status_id')->label('Status')->options(fn () => StatusLookup::forContext(Status::CTX_SUPPLIER)->pluck('name', 'id')),
            ])
            ->recordActions([
                EditAction::make(),
                Action::make('blacklist')
                    ->visible(fn (Supplier $record): bool => Perm::can('isms_suppliers', 'blacklist') && ! $record->is_blacklisted)
                    ->requiresConfirmation()
                    ->schema([
                        Textarea::make('reason')->required()->maxLength(500),
                    ])
                    ->action(function (Supplier $record, array $data): void {
                        app(SupplierService::class)->blacklist($record, $data['reason']);
                        Notification::make()->title('Supplier blacklisted.')->success()->send();
                    }),
                Action::make('unblacklist')
                    ->visible(fn (Supplier $record): bool => Perm::can('isms_suppliers', 'blacklist') && $record->is_blacklisted)
                    ->requiresConfirmation()
                    ->action(function (Supplier $record): void {
                        app(SupplierService::class)->unblacklist($record);
                        Notification::make()->title('Supplier reinstated.')->success()->send();
                    }),
                DeleteAction::make()
                    ->after(fn (Supplier $record) => AuditLog::record('supplier.deleted', $record, ['name' => $record->name])),
            ]);
    }

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