<?php

namespace App\Filament\Resources\Products;

use App\Filament\Resources\Products\Pages\ListStockAdjustments;
use App\Models\StockAdjustment;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;

class StockAdjustmentResource extends Resource
{
    protected static ?string $model = StockAdjustment::class;

    protected static ?string $slug = 'stock-adjustments';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-clipboard-document-list';

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

    protected static ?int $navigationSort = 4;

    protected static ?string $navigationLabel = 'Stock Adjustments';

    protected static ?string $pluralLabel = 'Stock Adjustments';

    protected static ?string $modelLabel = 'Stock Adjustment';

    public static function form(Schema $schema): Schema
    {
        return $schema;
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('product.name')
                    ->label('Product / Variant')
                    ->searchable()
                    ->sortable()
                    ->state(function (StockAdjustment $record): string {
                        $name = $record->product?->name ?? 'Deleted Product';
                        if ($record->variant) {
                            $options = $record->variant->options;
                            if (is_array($options)) {
                                $variantLabel = implode(', ', $options);
                                $name .= " ({$variantLabel})";
                            }
                        }
                        return $name;
                    }),
                TextColumn::make('sku')
                    ->label('SKU')
                    ->searchable()
                    ->state(function (StockAdjustment $record): string {
                        return $record->variant?->sku ?? ($record->product?->sku ?? '—');
                    }),
                TextColumn::make('event')
                    ->label('Event')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'manual' => 'Manual Adjustment',
                        'order_placed' => 'Order Placed',
                        'order_cancelled' => 'Order Cancelled',
                        'return_received' => 'Return Received',
                        default => ucfirst(str_replace('_', ' ', $state)),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'manual' => 'gray',
                        'order_placed' => 'warning',
                        'order_cancelled' => 'danger',
                        'return_received' => 'success',
                        default => 'gray',
                    }),
                TextColumn::make('change_amount')
                    ->label('Change')
                    ->badge()
                    ->state(fn (StockAdjustment $record): string => ($record->change_amount > 0 ? '+' : '') . $record->change_amount)
                    ->color(fn (StockAdjustment $record): string => $record->change_amount > 0 ? 'success' : 'danger'),
                TextColumn::make('flow')
                    ->label('Quantity Flow')
                    ->state(fn (StockAdjustment $record): string => "{$record->old_quantity} → {$record->new_quantity}"),
                TextColumn::make('order.order_number')
                    ->label('Order')
                    ->searchable()
                    ->url(fn (StockAdjustment $record): ?string => $record->order_id ? url('/admin/orders/' . $record->order_id . '/edit') : null)
                    ->placeholder('—'),
                TextColumn::make('user.name')
                    ->label('Adjusted By')
                    ->searchable()
                    ->placeholder('System'),
                TextColumn::make('created_at')
                    ->label('Date')
                    ->since()
                    ->sortable()
                    ->tooltip(fn ($record) => $record->created_at->format('M j, Y H:i')),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                SelectFilter::make('event')
                    ->options([
                        'manual' => 'Manual Adjustment',
                        'order_placed' => 'Order Placed',
                        'order_cancelled' => 'Order Cancelled',
                        'return_received' => 'Return Received',
                    ]),
            ])
            ->actions([
                // Read-only resource
            ])
            ->bulkActions([
                // Read-only resource
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListStockAdjustments::route('/'),
        ];
    }
}
