<?php

namespace App\Filament\Resources;

use App\Filament\Exports\LineStopExporter;
use App\Filament\Imports\LineStopImporter;
use App\Filament\Resources\LineStopResource\Pages;
use App\Filament\Resources\LineStopResource\RelationManagers;
use App\Models\LineStop;
use Doctrine\DBAL\Exception\InvalidColumnType\ColumnPrecisionRequired;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Tables\Actions\ExportAction;

class LineStopResource extends Resource
{
    protected static ?string $model = LineStop::class;

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

    protected static ?string $navigationGroup = 'Master Entries';

    protected static ?int $navigationSort = 7;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                    Forms\Components\TextInput::make('code')
                        ->required()
                        ->alphaNum()
                        ->unique(ignoreRecord: true)
                        ->minLength(3)
                        ->placeholder('Scan the valid code')
                        ->autofocus(true)
                        ->autocapitalize(autocapitalize: 'characters')
                        ->columnSpan(1)
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $code = $get('code');
                            if (!$code) {
                                $set('lsCodeError', 'Scan the valid code.');
                                return;
                            }
                            else
                            {
                                if (strlen($code) < 3) {
                                    $set('lsCodeError', 'Code must be at least 3 digits.');
                                    return;
                                }
                                else if (!preg_match('/^[a-zA-Z0-9]{3,}$/', $code)) {
                                    $set('code',null);
                                    $set('lsCodeError', 'Alpha-numeric only allowed.');
                                    return;
                                }
                                $set('lsCodeError', null);
                            }
                        })
                        ->extraAttributes(fn ($get) => [
                            'class' => $get('lsCodeError') ? 'border-red-500' : '',
                        ])
                        ->hint(fn ($get) => $get('lsCodeError') ? $get('lsCodeError') : null)
                        ->hintColor('danger'),
                    Forms\Components\TextInput::make('reason')
                        ->required()
                        ->placeholder('Scan the valid reason')
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $reason = $get('reason');
                            if (!$reason) {
                                $set('lsReasonError', 'Scan the valid reason.');
                                return;
                            }
                            else
                            {
                                $set('lsReasonError', null);
                            }
                        })
                        ->extraAttributes(fn ($get) => [
                            'class' => $get('lsReasonError') ? 'border-red-500' : '',
                        ])
                        ->hint(fn ($get) => $get('lsReasonError') ? $get('lsReasonError') : null)
                        ->hintColor('danger')
                        ->columnSpan(['default' => 1, 'sm' => 2]),
                    ])
                    ->columns(['default' => 1, 'sm' => 3]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                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('code')
                    ->label('Line Stop Code')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('reason')
                    ->label('Line Stop Reason')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->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()
                    ->label('Import Line Stops')
                    ->color('warning')
                    ->importer(LineStopImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import line stop');
                    }),
                ExportAction::make()
                    ->label('Export Line Stops')
                    ->color('warning')
                    ->exporter(LineStopExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export line stop');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListLineStops::route('/'),
            'create' => Pages\CreateLineStop::route('/create'),
            'view' => Pages\ViewLineStop::route('/{record}'),
            'edit' => Pages\EditLineStop::route('/{record}/edit'),
        ];
    }

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