<?php

namespace App\Filament\Imports;

use App\Models\AsrsItemValidation;
use App\Models\Plant;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Str;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;

class AsrsItemValidationImporter extends Importer
{
    protected static ?string $model = AsrsItemValidation::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('PLANT CODE')
                ->example('1000')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('item_code')
                ->exampleHeader('ITEM CODE')
                ->example('ITEM001')
                ->label('ITEM CODE')
                ->rules(['required']),
            ImportColumn::make('item_description')
                ->exampleHeader('ITEM DESCRIPTION')
                ->example('Item Description')
                ->label('ITEM DESCRIPTION'),
            ImportColumn::make('uom')
                ->exampleHeader('UOM')
                ->example('EA')
                ->label('UOM'),
            ImportColumn::make('material_type')
                ->exampleHeader('MATERIAL TYPE')
                ->example('Material Type')
                ->label('MATERIAL TYPE'),
            ImportColumn::make('material_group')
                ->exampleHeader('MATERIAL GROUP')
                ->example('Material Group')
                ->label('MATERIAL GROUP'),
        ];
    }

    public function resolveRecord(): ?AsrsItemValidation
    {
        $warnMsg = [];
        $plantCod = trim($this->data['plant']) ?? '';
        $iCode = trim($this->data['item_code']) ?? '';
        $itemDes = trim($this->data['item_description']) ?? '';
        $uom = trim($this->data['uom']) ?? '';
        $materialType = trim($this->data['material_type']) ?? '';
        $materialGroup = trim($this->data['material_group']) ?? '';
        $createdBy = Filament::auth()->user()?->name ?? '';
        $updatedBy = $createdBy;

        $plantId = null;

        if ($plantCod == null || $plantCod == '' || ! $plantCod) {
            $warnMsg[] = "Plant code can't be empty!";
        } elseif (! is_numeric($plantCod)) {
            $warnMsg[] = "Plant code '{$plantCod}' should contain only numeric values!";
        } elseif (Str::length($plantCod) < 4 || Str::length($plantCod) > 7) {
            $warnMsg[] = "Plant code '{$plantCod}' must be between 4 and 7 digits only!";
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCod)) {
            $warnMsg[] = "Invalid plant code '{$plantCod}' found!";
        } else {
            $plant = Plant::where('code', $plantCod)->first();
            if (! $plant) {
                $warnMsg[] = 'Plant not found!';
            } else {
                $plantId = $plant->id;
            }
        }
        if (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
            $warnMsg[] = 'Invalid item code found';
        }
        if (Str::length($itemDes) < 5) {
            $warnMsg[] = 'Invalid description found';
        }

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

        return AsrsItemValidation::updateOrCreate([
            'item_code' => $iCode,
            'plant_id' => $plant->id,
        ],
            [
                'item_description' => $itemDes,
                'uom' => trim($this->data['uom']),
                'material_type' => $materialType,
                'material_group' => $materialGroup,
                'created_by' => $createdBy,
                'updated_by' => $updatedBy,
            ]
        );
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your asrs item validation 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;
    }
}
