<?php

namespace App\Filament\Imports;

use App\Models\Item;
use App\Models\Plant;
use App\Models\WeightValidation;
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 WeightValidationImporter extends Importer
{
    protected static ?string $model = WeightValidation::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('item')
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example('123456')
                ->label('ITEM CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('obd_number')
                ->requiredMapping()
                ->exampleHeader('OBD Number')
                ->example('3RA00352')
                ->label('OBD Number')
                ->rules(['required']),
            ImportColumn::make('line_number')
                ->requiredMapping()
                ->exampleHeader('Line Number')
                ->example('1')
                ->label('Line Number')
                ->rules(['required']),
            ImportColumn::make('batch_number')
                ->requiredMapping()
                ->exampleHeader('Batch Number')
                ->example('2021217')
                ->label('Batch Number')
                ->rules(['required']),
            ImportColumn::make('heat_number')
                ->requiredMapping()
                ->exampleHeader('Heat Number')
                ->example('RSL-D1390')
                ->label('Heat Number')
                ->rules(['required']),
            ImportColumn::make('obd_weight')
                ->requiredMapping()
                ->exampleHeader('Actual Weight')
                ->example('3540.00')
                ->label('Actual Weight')
                ->rules(['required']),
            ImportColumn::make('vehicle_number')
                ->requiredMapping()
                ->exampleHeader('Vehicle Number')
                ->example('TN54AB1234')
                ->label('Vehicle Number')
                ->rules(['required']),
            ImportColumn::make('bundle_number')
                ->requiredMapping()
                ->exampleHeader('Bundle Number')
                ->example('1')
                ->label('Bundle Number')
                ->rules(['required']),
            ImportColumn::make('picked_weight')
                ->requiredMapping()
                ->exampleHeader('Picked Weight')
                ->example('1')
                ->label('Picked Weight')
                ->rules(['required']),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('scanned_by')
                ->requiredMapping()
                ->exampleHeader('Scanned By')
                ->example('User-1')
                ->label('Scanned By')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?WeightValidation
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $iCode = $this->data['item'];
        $plantId = null;
        $itemId = 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 {
                $plantId = $plant->id;
            }
        }

        if (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
            $warnMsg[] = 'Invalid item code found';
        } else {
            $itemCode = Item::where('code', $iCode)->first();
            if (! $itemCode) {
                $warnMsg[] = 'Item code not found';
            } else {
                if ($plantId) {
                    $itemAgainstPlant = Item::where('code', $iCode)->where('plant_id', $plantId)->first();
                    if (! $itemAgainstPlant) {
                        $warnMsg[] = 'Item code not found for the given plant';
                    } else {
                        $itemId = $itemAgainstPlant->id;
                    }
                }
            }
        }

        $obdNum = $this->data['obd_number'];
        if (Str::length($obdNum) < 8 || ! ctype_alnum($obdNum)) {
            $warnMsg[] = 'Invalid OBD number found';
        }
        $lineNum = $this->data['line_number'];
        if (Str::length($lineNum) < 1 || ! is_numeric($lineNum)) {
            $warnMsg[] = 'Invalid line number found';
        }
        $batchNum = $this->data['batch_number'];
        if (Str::length($batchNum) < 8 || ! is_numeric($batchNum)) {
            $warnMsg[] = 'Invalid batch number found';
        }
        $heatNum = $this->data['heat_number'];
        if (Str::length($heatNum) < 4) {
            $warnMsg[] = 'Invalid heat number found';
        }
        $actWeight = $this->data['obd_weight'];
        if (Str::length($actWeight) < 1 || ! is_numeric($actWeight)) {
            $warnMsg[] = 'Invalid actual weight found';
        }
        $vehicleNum = $this->data['vehicle_number'];
        if (Str::length($vehicleNum) < 10 || ! ctype_alnum($vehicleNum)) {
            $warnMsg[] = 'Invalid vehicle number found';
        }
        $bundleNum = $this->data['bundle_number'];
        if (Str::length($bundleNum) < 1 || ! is_numeric($bundleNum)) {
            $warnMsg[] = 'Invalid bundle number found';
        }
        $pickWeight = $this->data['picked_weight'];
        if (Str::length($pickWeight) < 1 || ! is_numeric($pickWeight)) {
            $warnMsg[] = 'Invalid picked weight found';
        }
        $scanBy = $this->data['scanned_by'];
        if (Str::length($scanBy) < 3 || ! ctype_alnum($scanBy)) {
            $warnMsg[] = 'Invalid scanned by name found';
        }

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

        return WeightValidation::updateOrCreate([
            'plant_id' => $plantId,
            'obd_number' => $obdNum,
            'line_number' => $lineNum,
        ],
            [
                'item_id' => $itemId,
                'batch_number' => $batchNum,
                'heat_number' => $heatNum,
                'obd_weight' => $actWeight,
                'vehicle_number' => $vehicleNum,
                'bundle_number' => $bundleNum,
                'picked_weight' => $pickWeight,
                'scanned_by' => $scanBy,
            ]
        );
        // return WeightValidation::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        // return new WeightValidation();
    }

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