<?php

namespace App\Filament\Resources;

use App\Filament\Exports\EmployeeMasterExporter;
use App\Filament\Imports\EmployeeMasterImporter;
use App\Filament\Resources\EmployeeMasterResource\Pages;
use App\Filament\Resources\EmployeeMasterResource\RelationManagers;
use App\Models\EmployeeMaster;
use Filament\Facades\Filament;
use Filament\Forms;
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;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Illuminate\Validation\Rule;

class EmployeeMasterResource extends Resource
{
    protected static ?string $model = EmployeeMaster::class;

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

    protected static ?string $navigationGroup = 'Gate Entry';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->required(),
                Forms\Components\TextInput::make('name')
                    ->label('Name')
                    ->required()
                    ->reactive()
                    ->extraInputAttributes([
                        'oninput' => 'this.value = this.value.replace(/[^a-zA-Z\s]/g, "")',
                    ]),
                Forms\Components\TextInput::make('code')
                    ->label('ID')
                    ->extraInputAttributes([
                        'oninput' => 'this.value = this.value.replace(/[^a-zA-Z0-9]/g, "")',])
                    ->required()
                    ->unique(
                        table: 'employee_masters',
                        column: 'code',
                        ignoreRecord: true
                    )
                    ->validationMessages([
                        'unique' => 'Duplicate employee code already exists.',
                    ]),
                Forms\Components\TextInput::make('department')
                    ->label('Department')
                    ->required(),
                // Forms\Components\TextInput::make('designation')
                    // ->label('Designation')
                    // ->extraInputAttributes([
                    //     'oninput' => 'this.value = this.value.replace(/[^a-zA-Z\s]/g, "")',])
                    // ->required(),
                Forms\Components\TextInput::make('email')
                    ->label('Email')
                    ->email()
                    ->required(),
                Forms\Components\TextInput::make('mobile_number')
                    ->label('Mobile Number')
                    ->length(10)
                    ->reactive()
                    ->extraInputAttributes([
                        'oninput' => 'this.value = this.value.replace(/[^0-9]/g, "").slice(0, 10)', // blocks non-numbers + limits to 10 chars
                        'maxlength' => 10,
                    ])
                    ->required()
                    ->unique(
                        table: 'employee_masters',
                        column: 'mobile_number',
                        ignoreRecord: true
                    )
                    ->validationMessages([
                        'unique' => 'Duplicate mobile number already exists.',
                    ]),
                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 ?? ''),
            ]);
    }

    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;
                    })
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('plant.name')
                    ->numeric()
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Name')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('code')
                    ->label('Employee ID')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('department')
                    ->label('Department')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                // Tables\Columns\TextColumn::make('designation')
                //     ->label('Designation')
                //     ->sortable()
                //     ->alignCenter()
                //     ->searchable(),
                Tables\Columns\TextColumn::make('email')
                    ->label('Email')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('mobile_number')
                    ->label('Mobile Number')
                    ->sortable()
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created by')
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated by')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->alignCenter(),
            ])
            ->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(EmployeeMasterImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import employee master');
                    }),
                ExportAction::make()
                    ->exporter(EmployeeMasterExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export employee master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListEmployeeMasters::route('/'),
            'create' => Pages\CreateEmployeeMaster::route('/create'),
            'view' => Pages\ViewEmployeeMaster::route('/{record}'),
            'edit' => Pages\EditEmployeeMaster::route('/{record}/edit'),
        ];
    }

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