<?php

namespace App\Filament\Imports;

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

class StickerPrintingImporter extends Importer
{
    protected static ?string $model = StickerPrinting::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('reference_number')
                ->exampleHeader('REFERENCE NUMBER')
                ->example('REF123456')
                ->label('REFERENCE NUMBER'),
            ImportColumn::make('serial_number')
                ->exampleHeader('SERIAL NUMBER')
                ->example('135245325212')
                ->label('SERIAL NUMBER'),
            // ImportColumn::make('created_by')
            //     ->exampleHeader('CREATED BY')
            //     ->example('RAW01234')
            //     ->label('CREATED BY'),
        ];
    }

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

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

        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!';
            }
        }

        if (Str::length($serial) < 9 || ! ctype_alnum($serial)) {
            $warnMsg[] = 'Invalid serial number found';
        } elseif ($plant) {
            $existing = StickerPrinting::where('plant_id', $plant->id)->where('serial_number', $serial)->first();
            if ($existing) {
                $warnMsg[] = "Serial number '{$serial}' already exists for plant '{$plantCod}'!"; // throw new RowImportFailedException("Serial number already exists for this plant!");
            }
        }

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

        StickerPrinting::Create([
            'plant_id' => $plant->id,
            'reference_number' => $this->data['reference_number'],
            'serial_number' => $this->data['serial_number'],
            'created_at' => now(),
            'updated_at' => now(),
            'created_by' => Filament::auth()->user()?->name,
        ]);

        return null;

        // return new StickerPrinting();
    }

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