<?php

namespace App\Filament\Resources;

use App\Filament\Exports\StickerPrintingExporter;
use App\Filament\Imports\StickerPrintingImporter;
use App\Filament\Resources\StickerPrintingResource\Pages;
use App\Models\Plant;
use App\Models\StickerPrinting;
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\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class StickerPrintingResource extends Resource
{
    protected static ?string $model = StickerPrinting::class;

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

    protected static ?string $navigationGroup = 'Sticker Reprint';

    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')
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->required()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');

                                if (! $plantId) {
                                    $set('reference_number', null);
                                    $set('serial_number', null);
                                    $set('ivPlantError', 'Please select a plant first.');
                                } else {
                                    $set('ivPlantError', null);
                                    $set('reference_number', null);
                                    $set('serial_number', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('ivPlantError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('ivPlantError') ? $get('ivPlantError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('reference_number')
                            ->label('Reference Number')
                            ->reactive()
                            ->readOnly(fn (callable $get) => ! empty($get('serial_number')))
                            ->extraAttributes([
                                'id' => 'invoice_number_input',
                                'x-data' => '{ value: "" }',
                                'x-model' => 'value',
                                'wire:keydown.enter.prevent' => 'processRef(value)',
                            ])
                            ->required(),
                        Forms\Components\TextInput::make('serial_number')
                            ->label('Serial Number')
                            ->reactive()
                           // ->required()
                            ->readOnly(fn (callable $get) => empty($get('reference_number')))
                            ->extraAttributes([
                                'id' => 'serial_number_input',
                                'x-data' => '{ value: "" }',
                                'x-model' => 'value',
                                'wire:keydown.enter.prevent' => 'processSno(value)',
                                // 'x-on:keydown.enter.prevent' => '$wire.processInvoice(value)',
                            ]),
                        // ->required(),
                        Forms\Components\View::make('forms.components.print-button'),

                        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.name')
                    ->label('Plant')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('reference_number')
                    ->label('Reference Number')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->searchable()
                    ->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(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->importer(StickerPrintingImporter::class)
                    ->label('Import Sticker Printing')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import sticker printing');
                    }),
                ExportAction::make()
                    ->exporter(StickerPrintingExporter::class)
                    ->label('Export Sticker Printing')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export sticker printing');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerPrintings::route('/'),
            'create' => Pages\CreateStickerPrinting::route('/create'),
            'view' => Pages\ViewStickerPrinting::route('/{record}'),
            'edit' => Pages\EditStickerPrinting::route('/{record}/edit'),
        ];
    }

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