<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BodegaResource\Pages;
use App\Filament\Resources\BodegaResource\RelationManagers;
use App\Models\Bodega;
use Filament\Forms\Form;
use Filament\Tables\Table;
use Filament\Resources\Resource;
use Filament\Forms\Components\TextInput;
use Filament\Tables;
use Filament\Notifications\Notification;

class BodegaResource extends Resource
{
    protected static ?string $model = Bodega::class;

    protected static ?string $navigationIcon = 'heroicon-o-cube';
    protected static ?string $navigationGroup = 'Operación';
    protected static ?string $navigationLabel = 'Bodegas';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                TextInput::make('nombre')
                    ->required()
                    ->maxLength(255),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')->sortable(),
                Tables\Columns\TextColumn::make('nombre')->searchable(),
                Tables\Columns\TextColumn::make('stock_total')
                    ->label('Stock total')
                    ->getStateUsing(fn (Bodega $record) => $record->stock_total),
            ])
            ->filters([
                // Puedes añadir filtros aquí si lo deseas
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make()
                    ->before(function (Bodega $record, Tables\Actions\DeleteAction $action) {
                        $hasStockProductos = $record->productos()->wherePivot('stock', '>', 0)->exists();
                        $hasStockVariantes = $record->variantes()->wherePivot('stock', '>', 0)->exists();
                        
                        if ($hasStockProductos || $hasStockVariantes) {
                            Notification::make()
                                ->warning()
                                ->title('No se puede eliminar')
                                ->body('Esta bodega tiene productos con stock asignado. Debe vaciar el stock antes de eliminarla.')
                                ->persistent()
                                ->send();
                            
                            $action->cancel();
                        }
                    }),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make()
                    ->action(function (Tables\Actions\DeleteBulkAction $action, \Illuminate\Database\Eloquent\Collection $records) {
                        foreach ($records as $record) {
                            $hasStockProductos = $record->productos()->wherePivot('stock', '>', 0)->exists();
                            $hasStockVariantes = $record->variantes()->wherePivot('stock', '>', 0)->exists();
                            
                            if ($hasStockProductos || $hasStockVariantes) {
                                Notification::make()
                                    ->warning()
                                    ->title('No se puede eliminar')
                                    ->body("La bodega '{$record->nombre}' tiene productos con stock asignado. No se eliminó ninguna bodega.")
                                    ->persistent()
                                    ->send();
                                
                                $action->cancel();
                                return;
                            }
                        }
                        
                        $records->each->delete();
                        
                        Notification::make()
                            ->success()
                            ->title('Bodegas eliminadas')
                            ->body('Las bodegas seleccionadas han sido eliminadas.')
                            ->send();
                    }),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\ProductosRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBodegas::route('/'),
            'create' => Pages\CreateBodega::route('/create'),
            'edit' => Pages\EditBodega::route('/{record}/edit'),
        ];
    }
}
?>
