<?php

namespace App\Filament\Resources;

use App\Filament\Exports\PlantExporter;
use App\Filament\Imports\PlantImporter;
use App\Filament\Resources\PlantResource\Pages;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Forms\Get;
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;

// use Illuminate\Validation\Rule;

class PlantResource extends Resource
{
    protected static ?string $model = Plant::class;

    protected static ?string $navigationIcon = 'heroicon-s-building-office-2';

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

    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\TextInput::make('code')
                            ->label('Code')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->integer()
                            ->reactive()
                            ->placeholder('Scan the valid code')
                            ->autofocus(true)
                            // ->minLength(4)
                            // ->maxLength(7)
                            ->minValue(1000)
                            ->maxValue(9999999)
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $codeId = $get('code');
                                // Ensure `linestop_id` is not cleared
                                if (! $codeId) {
                                    $set('pCodeError', 'Scan the valid code.');

                                    return;
                                } else {
                                    if (strlen($codeId) < 4 || strlen($codeId) > 7) {
                                        $set('pCodeError', 'Code must be between 4 and 7 digits only!'); // Code must be at least 4 digits.

                                        return;
                                    }
                                    // if (!preg_match('/^[1-9][0-9]{3,}$/', $codeId)) {
                                    //     $set('code',null);
                                    //     $set('pCodeError', 'Code should not begin with zero and must contain 4 digit number.');
                                    //     return;
                                    // }
                                    $set('pCodeError', null);
                                }
                            })
                            // ->rule(function (callable $get) {
                            //     return Rule::unique('plants', 'code')->ignore($get('id'));
                            // })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pCodeError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pCodeError') ? $get('pCodeError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('company_id')
                            ->label('Company')
                            ->placeholder('Choose the valid company nany')
                            ->relationship('company', 'name')
                            ->required()
                            ->reactive()
                            ->default(function () {
                                return optional(Plant::latest()->first())->company_id;
                            })
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $companyId = $get('company_id');
                                // Ensure `linestop_id` is not cleared
                                if (! $companyId) {
                                    $set('pCompanyError', 'Please select a company first.');

                                    return;
                                } else {
                                    $set('pCompanyError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pCompanyError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pCompanyError') ? $get('pCompanyError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->label('Name')
                            ->placeholder('Scan the valid name')
                            ->unique(ignoreRecord: true)
                            // ->columnSpanFull()
                            ->reactive()
                            ->minLength(5)
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $nameId = $get('name');
                                // Ensure `linestop_id` is not cleared
                                if (! $nameId) {
                                    $set('pNameError', 'Scan the valid name.');

                                    return;
                                } else {
                                    $set('pNameError', null);
                                }
                            })
                            // ->rule(function (callable $get) {
                            //     return Rule::unique('plants', 'name')->ignore($get('id'));
                            // })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pNameError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pNameError') ? $get('pNameError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('warehouse_number')
                            // ->required()
                            ->label('Warehouse Number')
                            ->placeholder('Scan the valid warehouse number')
                            ->unique(ignoreRecord: true)
                            ->reactive()
                            ->numeric()
                            ->length(3),
                        // ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        //     $codeId = $get('warehouse_number');
                        //     // Ensure `linestop_id` is not cleared
                        //     if (! $codeId) {
                        //         $set('wNumberError', 'Scan the valid warehouse number.');

                        //         return;
                        //     } else {
                        //         if (strlen($codeId) != 3) {
                        //             $set('wNumberError', 'Warehouse number must be exactly 3 digits!');

                        //             return;
                        //         }
                        //         $set('wNumberError', null);
                        //     }
                        // })
                        // ->extraAttributes(fn ($get) => [
                        //     'class' => $get('wNumberError') ? 'border-red-500' : '',
                        // ])
                        // ->hint(fn ($get) => $get('wNumberError') ? $get('wNumberError') : null)
                        // ->hintColor('danger'),
                        Forms\Components\Textarea::make('address')
                            ->required()
                            ->label('Address')
                            ->placeholder('Scan the valid address')
                            ->unique(ignoreRecord: true)
                            ->columnSpanFull()
                            ->reactive()
                            ->minLength(5)
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $nameId = $get('address');
                                // Ensure `linestop_id` is not cleared
                                if (! $nameId) {
                                    $set('pAddressError', 'Scan the valid address.');

                                    return;
                                } else {
                                    $set('pAddressError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pAddressError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pAddressError') ? $get('pAddressError') : 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('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;
                    })
                    ->toggleable(isToggledHiddenByDefault: false),
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->numeric()
                    ->alignCenter()
                    ->sortable()
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('code')
                    ->label('Code')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('warehouse_number')
                    ->label('Warehouse Number')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('address')
                    ->label('Address')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('company.name')
                    ->label('Company')
                    ->alignCenter()
                    ->sortable(),
                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 Plants')
                    ->color('warning')
                    ->importer(PlantImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import plant');
                    }),
                ExportAction::make()
                    ->label('Export Plants')
                    ->color('warning')
                    ->exporter(PlantExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export plant');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPlants::route('/'),
            'create' => Pages\CreatePlant::route('/create'),
            'view' => Pages\ViewPlant::route('/{record}'),
            'edit' => Pages\EditPlant::route('/{record}/edit'),
        ];
    }

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