<?php

namespace App\Filament\Resources;

use App\Filament\Resources\StickerValidationResource\Pages;
use App\Filament\Resources\StickerValidationResource\RelationManagers;
use App\Models\Machine;
use App\Models\StickerValidation;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class StickerValidationResource extends Resource
{
    protected static ?string $model = StickerValidation::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?string $navigationGroup = 'Customized Sticker Printing';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->reactive()
                    ->relationship('plant', 'name')
                    ->required(),
                Forms\Components\Select::make('machine_id')
                    ->label('Work Center')
                    ->required()
                    ->reactive()
                    ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                Forms\Components\TextInput::make('production_order')
                    ->label('Production Order')
                    ->reactive()
                    ->extraAttributes([
                        'id' => 'production_order_input',
                        'x-data' => '{ value: "" }',
                        'x-model' => 'value',
                        'wire:keydown.enter.prevent' => 'processProOrder(value)',
                    ]),
                Forms\Components\TextInput::make('serial_number')
                    ->label('Serial Number')
                    ->reactive()
                    ->extraAttributes([
                        'id' => 'serial_number_input',
                        'x-data' => '{ value: "" }',
                        'x-model' => 'value',
                        'wire:keydown.enter.prevent' => 'processSno(value)',
                    ]),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By')
                    ->default(Filament::auth()->user()?->name),
           ])
                ->columns(4),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant.code')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('production_order')
                    ->label('Production Order')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerValidations::route('/'),
            'create' => Pages\CreateStickerValidation::route('/create'),
            'view' => Pages\ViewStickerValidation::route('/{record}'),
            'edit' => Pages\EditStickerValidation::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
