<?php

namespace App\Filament\Imports;

use App\Models\Plant;
use App\Models\User;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Spatie\Permission\Models\Role;
use Str;

class UserImporter extends Importer
{
    protected static ?string $model = User::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant_id')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code'),
            ImportColumn::make('name')
                ->requiredMapping()
                ->exampleHeader('Name')
                ->example('RAW00001')
                ->label('Name')
                ->rules(['required']), // , 'max:255'
            ImportColumn::make('email')
                ->requiredMapping()
                ->exampleHeader('E-Mail')
                ->example('RAW00001@cripumps.com')
                ->label('E-Mail')
                ->rules(['required', 'email']), // , 'max:255'
            ImportColumn::make('password')
                ->requiredMapping()
                ->exampleHeader('Password')
                ->example('RAW00001')
                ->label('Password')
                ->rules(['required']), // , 'max:255'
            ImportColumn::make('roles')
                ->requiredMapping()
                ->exampleHeader('Roles')
                ->example('Employee')
                ->label('Roles')
                ->rules(['nullable', 'string']), // Optional roles
        ];
    }

    public function resolveRecord(): ?User
    {
        $warnMsg = [];
        $plantCod = $this->data['plant_id'];
        $plant = null;
        $user = $this->data['name'];
        $mail = $this->data['email'];
        $pass = $this->data['password'];
        $restrictedUsers = ['Admin', 'Dhanabalan S', 'Ranjith B'];
        $adminUser = Filament::auth()->user()?->name;

        if (Str::length($plantCod) > 0 && (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod))) {
            $warnMsg[] = 'Invalid plant code found!';
        } elseif (Str::length($plantCod) <= 0) {
            $plant = null;
            $plantCod = null;
        } else {
            $plant = Plant::where('code', $plantCod)->first();
            if (! $plant) {
                $warnMsg[] = 'Plant not found';
            } else {
                $plant = $plant->id ?? null;
            }
        }

        if (Str::length($user) < 3) {
            $warnMsg[] = 'Invalid user name found!';
        }
        // || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])
        if (Str::length($mail) < 5) {
            $warnMsg[] = 'Invalid email found!';
        }
        if (Str::length($pass) < 3) {
            $warnMsg[] = 'Invalid password found!';
        }
        // Validate roles if provided
        $roles = [];
        if (! empty($this->data['roles'])) {
            $roles = collect(explode(',', $this->data['roles']))
                ->map(fn ($role) => trim($role))
                ->filter()
                ->toArray();

            foreach ($roles as $roleName) {
                if (! Role::where('name', $roleName)->exists()) {
                    $warnMsg[] = "Role : '{$roleName}' does not exist!";
                }
            }
        } else {
            $warnMsg[] = 'User roles not found!';
        }

        if (! in_array($adminUser, $restrictedUsers, true) && in_array($user, $restrictedUsers, true)) {
            throw new RowImportFailedException("You don't have permission to import user with name '{$user}'!");
        }

        if (! empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        $user = User::updateOrCreate([
            'email' => $mail,
        ],
            [
                'name' => $user,
                'password' => $pass,
                'plant_id' => $plant,
            ]);

        // Assign roles
        if (! empty($roles)) {
            $user->syncRoles($roles);
        }

        return null;
        // return User::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $mail,
        // ]);

        // return new User();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your user import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.';
        }

        return $body;
    }
}
