<?php

namespace App\Filament\Imports;

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

class GrMasterImporter extends Importer
{
    protected static ?string $model = GrMaster::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('630214')
                ->label('Item Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('serial_number')
                ->requiredMapping()
                ->exampleHeader('Serial Number')
                ->example('11023567567567')
                ->label('Serial Number')
                ->rules(['required']),
            ImportColumn::make('gr_number')
                ->requiredMapping()
                ->exampleHeader('GR Number')
                ->example('67345237')
                ->label('GR Number')
                ->rules(['required']),
            ImportColumn::make('created_by')
                ->requiredMapping()
                ->exampleHeader('Created By')
                ->example('Admin')
                ->label('Created By')
                ->rules(['required']),
            // ImportColumn::make('updated_by'),
        ];
    }

    public function resolveRecord(): ?GrMaster
    {
        // return GrMaster::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $item = null;

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

        if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) {
            $warnMsg[] = 'Invalid serial number found';
        }

        if (empty($this->data['gr_number'])) {
            $warnMsg[] = 'GR Number cannot be empty.';
        }

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

        if (! empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        } else { // if (empty($warnMsg))
            $grMaster = GrMaster::where('plant_id', $plant->id)
                ->where('serial_number', $this->data['serial_number'])
                ->latest()
                ->first();

            if ($grMaster) {
                throw new RowImportFailedException('Serial number already exist!');
            }
        }

        GrMaster::updateOrCreate([
            'plant_id' => $plant->id,
            'item_id' => $item->id,
            'serial_number' => $this->data['serial_number'],
            'gr_number' => $this->data['gr_number'] ?? null,
            'created_by' => $this->data['created_by'],
        ]);

        return null;
        // return new GrMaster();
    }

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