<?php

namespace App\Filament\Resources;

use App\Filament\Exports\BlockExporter;
use App\Filament\Imports\BlockImporter;
use App\Filament\Resources\BlockResource\Pages;
use App\Models\Block;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
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;
use Illuminate\Validation\Rule;

class BlockResource extends Resource
{
    protected static ?string $model = Block::class;

    protected static ?string $navigationIcon = 'heroicon-c-building-library';

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

    protected static ?int $navigationSort = 3;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->required()
                            // ->unique(ignoreRecord: true)
                            ->placeholder('Scan the valid name')
                            ->autofocus(true)
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $nameId = $get('name');
                                // Ensure `linestop_id` is not cleared
                                if (!$nameId) {
                                    $set('bNameError', 'Scan the valid name.');
                                    return;
                                }
                                else
                                {
                                    $set('bNameError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('bNameError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('bNameError') ? $get('bNameError') : null)
                            ->hintColor('danger')
                            ->rule(function (callable $get) {
                                return Rule::unique('blocks', 'name')
                                    ->where('plant_id', $get('plant_id'))
                                    ->ignore($get('id')); // Ignore current record during updates
                            }),
                        Forms\Components\Select::make('plant_id')
                            ->relationship('plant', 'name')
                            // ->unique(ignoreRecord: true)
                            ->required()
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;
                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                            })
                            ->default(function () {
                                return optional(Block::latest()->first())->plant_id;
                            })
                            ->disabled(fn (Get $get) => !empty($get('id')))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $nameId = $get('plant_id');
                                // Ensure `linestop_id` is not cleared
                                if (!$nameId) {
                                    $set('bPlantError', 'Please select a plant first.');
                                    return;
                                }
                                else
                                {
                                    $set('bPlantError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('bPlantError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('bPlantError') ? $get('bPlantError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->readOnly(),
                        ])
                    ->columns(2),
            ]);
    }

    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('name')
                    //->unique(ignoreRecord: true)
                    ->label('Block')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->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 Blocks')
                    ->color('warning')
                    ->importer(BlockImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import block');
                    }),
                ExportAction::make()
                    ->label('Export Blocks')
                    ->color('warning')
                    ->exporter(BlockExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export block');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBlocks::route('/'),
            'create' => Pages\CreateBlock::route('/create'),
            'view' => Pages\ViewBlock::route('/{record}'),
            'edit' => Pages\EditBlock::route('/{record}/edit'),
        ];
    }

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