<?php

namespace App\Filament\Imports;

use App\Models\Item;
use App\Models\Plant;
use App\Models\ProcessOrder;
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 Str;

class ProcessOrderImporter extends Importer
{
    protected static ?string $model = ProcessOrder::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')
                ->requiredMapping()
                ->exampleHeader('ITEM CODE')
                ->example('123456')
                ->label('ITEM CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('process_order')
                ->exampleHeader('PROCESS ORDER')
                ->example('202500123456')
                ->label('PROCESS ORDER')
                ->rules(['required']),
            ImportColumn::make('created_by')
                ->exampleHeader('CREATED BY')
                ->example('RAW01234')
                ->label('CREATED BY')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?ProcessOrder
    {
        $warnMsg = [];
        $plant = Plant::where('code', $this->data['plant'])->first();
        $itemCode = Item::where('code', $this->data['item'])->first();
        $iCode = trim($this->data['item']);

        if (! $plant) {
            $warnMsg[] = 'Plant not found';
        } elseif (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
            $warnMsg[] = 'Invalid item code found';
        } elseif (! $itemCode) {
            $warnMsg[] = 'Item Code not found';
        }

        $processOrder = trim($this->data['process_order'] ?? '');

        if ($processOrder == '') {
            $warnMsg[] = 'Process Order cannot be empty';
        }

        $user = User::where('name', $this->data['created_by'])->first();
        if (! $user) {
            $warnMsg[] = 'User not found';
        }

        if ($plant && $processOrder != '') {

            $existingOrder = ProcessOrder::where('plant_id', $plant->id)
                ->where('process_order', $processOrder)
                ->first();

            if ($existingOrder && $existingOrder->item_id !== ($itemCode->id ?? null)) {
                $warnMsg[] = 'Same Process Order already exists for this Plant with a different Item Code';
            }
        }

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

        return ProcessOrder::create([
            'plant_id' => $plant->id,
            'item_id' => $itemCode->id,
            'process_order' => trim($this->data['process_order']),
            'coil_number' => '0',
            'order_quantity' => 0,
            'received_quantity' => 0,
            'created_by' => $user->name,
        ]);

        // return new ProcessOrder();
    }

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