<?php

namespace App\Filament\Imports;

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

class ItemImporter extends Importer
{
    protected static ?string $model = Item::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('category')
                ->requiredMapping()
                ->exampleHeader('Category')
                ->example('Submersible Motor')
                ->label('Category'),
            ImportColumn::make('code')
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example('123456')
                ->label('Item Code')
                ->rules(['required']),
            ImportColumn::make('description')
                ->requiredMapping()
                ->exampleHeader('Description')
                ->example('Testing Model Description 1')
                ->label('Description')
                ->rules(['required']),
            ImportColumn::make('hourly_quantity')
                ->requiredMapping()
                ->exampleHeader('Hourly Quantity')
                ->example('25')
                ->label('Hourly Quantity')
                ->numeric()
                ->rules(['required', 'integer']),
            ImportColumn::make('uom')
                ->requiredMapping()
                ->exampleHeader('Unit of Measure')
                ->example('EA')
                ->label('Unit of Measure'),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Name')
                ->example('Ransar Industries-I')
                ->label('Plant Name')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?Item
    {
        $warnMsg = [];
        $iCode = trim($this->data['code']);
        $description = trim($this->data['description']);
        $plant = Plant::where('name', $this->data['plant'])->first();
        if (!$plant) {
            $warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "'
        }
        if (Str::length($iCode) < 6 || !ctype_alnum($iCode)) {
            $warnMsg[] = "Invalid item code found";
        }
        // if (Str::length($this->data['uom']) <= 0) {
        //     $warnMsg[] = "Invalid unit of measure found";
        // }
        if (Str::length($description) < 5) {
            $warnMsg[] = "Invalid description found";
        }
        if (Str::length($this->data['hourly_quantity']) < 0 || !is_numeric($this->data['hourly_quantity']) || $this->data['hourly_quantity'] <= 0) {
            $warnMsg[] = "Invalid hourly quantity found";
        }
        if (!empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }
        return Item::updateOrCreate([
                'code' => $iCode,
                'plant_id' => $plant->id
            ],
            [
                'category' => trim($this->data['category']),
                'description' => $description,
                'hourly_quantity' => $this->data['hourly_quantity'],
                'uom' => trim($this->data['uom'])
            ]
        );
        // return new Item;
    }

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