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

        if (Str::length($this->data['name']) < 1) {
            $warnMsg[] = "User name not found!";
        }
        // || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])
        if (Str::length($this->data['email']) < 5) {
            $warnMsg[] = "Invalid email found!";
        }
        if (Str::length($this->data['password']) < 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 (!empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        $user = User::updateOrCreate([
            'email' => $this->data['email'],
        ],
        [
            'name' => $this->data['name'],
            'password' => $this->data['password'],
            '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' => $this->data['email'],
        // ]);

        //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;
    }
}
