<?php

namespace App\Filament\Imports;

use App\Models\Item;
use App\Models\Plant;
use App\Models\StickerMaster;
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 StickerMasterImporter extends Importer
{
    protected static ?string $model = StickerMaster::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('serial_number_motor')
                ->requiredMapping()
                ->exampleHeader('Serial Number Motor')
                ->label('SERIAL NUMBER MOTOR')
                ->example('1'),
            ImportColumn::make('serial_number_pump')
                ->requiredMapping()
                ->exampleHeader('Serial Number Pump')
                ->label('SERIAL NUMBER PUMP')
                ->example('1'),
            ImportColumn::make('serial_number_pumpset')
                ->requiredMapping()
                ->exampleHeader('Serial Number PumpSet')
                ->label('SERIAL NUMBER PUMPSET')
                ->example(''),
            ImportColumn::make('pack_slip_motor')
                ->requiredMapping()
                ->exampleHeader('Pack Slip Motor')
                ->label('PACK SLIP MOTOR')
                ->example('1'),
            ImportColumn::make('pack_slip_pump')
                ->requiredMapping()
                ->exampleHeader('Pack Slip Pump')
                ->label('PACK SLIP PUMP')
                ->example('1'),
            ImportColumn::make('pack_slip_pumpset')
                ->requiredMapping()
                ->exampleHeader('Pack Slip PumpSet')
                ->label('PACK SLIP PUMPSET')
                ->example(''),
            ImportColumn::make('name_plate_motor')
                ->requiredMapping()
                ->exampleHeader('Name Plate Motor')
                ->label('NAME PLATE MOTOR')
                ->example('1'),
            ImportColumn::make('name_plate_pump')
                ->requiredMapping()
                ->exampleHeader('Name Plate Pump')
                ->label('NAME PLATE PUMP')
                ->example('1'),
            ImportColumn::make('name_plate_pumpset')
                ->requiredMapping()
                ->exampleHeader('Name Plate PumpSet')
                ->label('NAME PLATE PUMPSET')
                ->example(''),
            ImportColumn::make('tube_sticker_motor')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker Motor')
                ->label('TUBE STICKER MOTOR')
                ->example('1'),
            ImportColumn::make('tube_sticker_pump')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker Pump')
                ->label('TUBE STICKER PUMP')
                ->example('1'),
            ImportColumn::make('tube_sticker_pumpset')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker PumpSet')
                ->label('TUBE STICKER PUMPSET')
                ->example(''),
            ImportColumn::make('warranty_card')
                ->requiredMapping()
                ->exampleHeader('Warranty Card')
                ->label('WARRANTY CARD')
                ->example('1'),
            ImportColumn::make('part_validation1')
                ->requiredMapping()
                ->exampleHeader('Part Validation 1')
                ->label('PART VALIDATION 1')
                ->example('12345'),
            ImportColumn::make('part_validation2')
                ->requiredMapping()
                ->exampleHeader('Part Validation 2')
                ->label('PART VALIDATION 2')
                ->example('23456'),
            ImportColumn::make('part_validation3')
                ->requiredMapping()
                ->exampleHeader('Part Validation 3')
                ->label('PART VALIDATION 3')
                ->example('34567'),
            ImportColumn::make('part_validation4')
                ->requiredMapping()
                ->exampleHeader('Part Validation 4')
                ->label('PART VALIDATION 4')
                ->example('45678'),
            ImportColumn::make('part_validation5')
                ->requiredMapping()
                ->exampleHeader('Part Validation 5')
                ->label('PART VALIDATION 5')
                ->example('56789'),
            ImportColumn::make('laser_part_validation1')
                ->requiredMapping()
                ->exampleHeader('Laser Part Validation 1')
                ->label('LASER PART VALIDATION 1')
                ->example('67890'),
            ImportColumn::make('laser_part_validation2')
                ->requiredMapping()
                ->exampleHeader('Laser Part Validation 2')
                ->label('LASER PART VALIDATION 2')
                ->example('78901'),
            ImportColumn::make('panel_box_code')
                ->requiredMapping()
                ->exampleHeader('Panel Box Code')
                ->label('PANEL BOX CODE')
                ->example('123456'),
            ImportColumn::make('load_rate')
                ->requiredMapping()
                ->integer()
                ->exampleHeader('Load Rate')
                ->label('LOAD RATE')
                ->example('0')
                ->rules(['required']),
            ImportColumn::make('material_type')
                ->requiredMapping()
                ->integer()
                ->exampleHeader('Material Type')
                ->label('MATERIAL TYPE')
                ->example(''),
            ImportColumn::make('bundle_quantity')
                ->requiredMapping()
                ->integer()
                ->exampleHeader('Bundle Quantity')
                ->label('BUNDLE QUANTITY')
                ->example(''),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?StickerMaster
    {
        $warnMsg = [];
        $plantCod = trim($this->data['plant']);
        $itemCod = trim($this->data['item']);
        $panelCod = trim($this->data['panel_box_code']);
        $plant = null;
        $item = null;
        $plantId = null;
        $itemId = null;
        $parts = null;
        $validParts = null;
        $part1 = trim($this->data['part_validation1']);
        $part2 = trim($this->data['part_validation2']);
        $part3 = trim($this->data['part_validation3']);
        $part4 = trim($this->data['part_validation4']);
        $part5 = trim($this->data['part_validation5']);
        $laserPart1 = trim($this->data['laser_part_validation1']);
        $laserPart2 = trim($this->data['laser_part_validation2']);
        $SerialNumberMotor = trim($this->data['serial_number_motor']) ?? null;
        $SerialNumberMotor = ($SerialNumberMotor == '0') ? null : $SerialNumberMotor;
        $SerialNumberPump = trim($this->data['serial_number_pump']) ?? null;
        $SerialNumberPump = ($SerialNumberPump == '0') ? null : $SerialNumberPump;
        $SerialNumberPumpSet = trim($this->data['serial_number_pumpset']) ?? null;
        $SerialNumberPumpSet = ($SerialNumberPumpSet == '0') ? null : $SerialNumberPumpSet;
        $PackSlipMotor = trim($this->data['pack_slip_motor']) ?? null;
        $PackSlipMotor = ($PackSlipMotor == '0') ? null : $PackSlipMotor;
        $PackSlipPump = trim($this->data['pack_slip_pump']) ?? null;
        $PackSlipPump = ($PackSlipPump == '0') ? null : $PackSlipPump;
        $PackSlipPumpSet = trim($this->data['pack_slip_pumpset']) ?? null;
        $PackSlipPumpSet = ($PackSlipPumpSet == '0') ? null : $PackSlipPumpSet;
        $NamePlateMotor = trim($this->data['name_plate_motor']) ?? null;
        $NamePlateMotor = ($NamePlateMotor == '0') ? null : $NamePlateMotor;
        $NamePlatePump = trim($this->data['name_plate_pump']) ?? null;
        $NamePlatePump = ($NamePlatePump == '0') ? null : $NamePlatePump;
        $NamePlatePumpSet = trim($this->data['name_plate_pumpset']) ?? null;
        $NamePlatePumpSet = ($NamePlatePumpSet == '0') ? null : $NamePlatePumpSet;
        $TubeStickMotor = trim($this->data['tube_sticker_motor']) ?? null;
        $TubeStickMotor = ($TubeStickMotor == '0') ? null : $TubeStickMotor;
        $TubeStickPump = trim($this->data['tube_sticker_pump']) ?? null;
        $TubeStickPump = ($TubeStickPump == '0') ? null : $TubeStickPump;
        $TubeStickPumpSet = trim($this->data['tube_sticker_pumpset']) ?? null;
        $TubeStickPumpSet = ($TubeStickPumpSet == '0') ? null : $TubeStickPumpSet;
        $WarrantyCard = trim($this->data['warranty_card']) ?? null;
        $WarrantyCard = ($WarrantyCard == '0') ? null : $WarrantyCard;
        $LoadRate = $this->data['load_rate'] ?? 0;
        $BundleQuantity = $this->data['bundle_quantity'] ?? null;
        $MaterialType = $this->data['material_type'] ?? null;

        $createdBy = Filament::auth()->user()->name;
        $updatedBy = Filament::auth()->user()->name;
        if ($plantCod == null || $plantCod == '') {
            $warnMsg[] = "Plant code can't be empty!";
        } elseif (! is_numeric($plantCod)) {
            $warnMsg[] = 'Plant code should contain only numeric values!';
        } elseif (Str::length($plantCod) < 4 || Str::length($plantCod) > 7) {
            $warnMsg[] = 'Plant code must be between 4 and 7 digits only!';
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $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($itemCod) < 6 || ! ctype_alnum($itemCod)) {
                $warnMsg[] = 'Invalid item code found!';
            } else {
                $item = Item::where('code', $itemCod)->first();
                if (! $item) {
                    $warnMsg[] = 'Item code not found!';
                } else {
                    $item = Item::where('code', $itemCod)->where('plant_id', $plantId)->first();
                    if (! $item) {
                        $warnMsg[] = 'Item code not found for the plant!';
                    } else {
                        $itemId = $item->id;

                        if (! $laserPart1 && ! (Str::length($laserPart2) == 1 && is_numeric($laserPart2))) {
                            $laserPart1 = $laserPart2;
                            $laserPart2 = null;
                        }

                        if (Str::length($panelCod) > 0 && (Str::length($panelCod) < 6 || ! ctype_alnum($panelCod))) {
                            $warnMsg[] = 'Invalid panel box code found!';
                        } elseif ($panelCod) {
                            $parts = [$part1, $part2, $part3, $part4];
                            $validParts = array_values(array_filter($parts, fn ($p) => ! empty($p)));
                            [$part1, $part2, $part3, $part4] = array_pad($validParts, 4, '');
                        } else {
                            $parts = [$part1, $part2, $part3, $part4, $part5];
                            $validParts = array_values(array_filter($parts, fn ($p) => ! empty($p)));
                            [$part1, $part2, $part3, $part4, $part5] = array_pad($validParts, 5, '');
                        }

                        if (Str::length($SerialNumberMotor) > 0 && (! is_numeric($SerialNumberMotor) || $SerialNumberMotor < 1)) {
                            $warnMsg[] = "Serial number motor must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($SerialNumberPump) > 0 && (! is_numeric($SerialNumberPump) || $SerialNumberPump < 1)) {
                            $warnMsg[] = "Serial number pump must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($SerialNumberPumpSet) > 0 && (! is_numeric($SerialNumberPumpSet) || $SerialNumberPumpSet < 1)) {
                            $warnMsg[] = "Serial number pumpset must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($PackSlipMotor) > 0 && (! is_numeric($PackSlipMotor) || $PackSlipMotor < 1)) {
                            $warnMsg[] = "Pack slip motor must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($PackSlipPump) > 0 && (! is_numeric($PackSlipPump) || $PackSlipPump < 1)) {
                            $warnMsg[] = "Pack slip pump must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($PackSlipPumpSet) > 0 && (! is_numeric($PackSlipPumpSet) || $PackSlipPumpSet < 1)) {
                            $warnMsg[] = "Pack slip pumpset must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($NamePlateMotor) > 0 && (! is_numeric($NamePlateMotor) || $NamePlateMotor < 1)) {
                            $warnMsg[] = "Name plate motor must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($NamePlatePump) > 0 && (! is_numeric($NamePlatePump) || $NamePlatePump < 1)) {
                            $warnMsg[] = "Name plate pump must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($NamePlatePumpSet) > 0 && (! is_numeric($NamePlatePumpSet) || $NamePlatePumpSet < 1)) {
                            $warnMsg[] = "Name plate pumpset must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($TubeStickMotor) > 0 && (! is_numeric($TubeStickMotor) || $TubeStickMotor < 1)) {
                            $warnMsg[] = "Tube sticker motor must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($TubeStickPump) > 0 && (! is_numeric($TubeStickPump) || $TubeStickPump < 1)) {
                            $warnMsg[] = "Tube sticker pump must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($TubeStickPumpSet) > 0 && (! is_numeric($TubeStickPumpSet) || $TubeStickPumpSet < 1)) {
                            $warnMsg[] = "Tube sticker pumpset must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($WarrantyCard) > 0 && (! is_numeric($WarrantyCard) || $WarrantyCard < 1)) {
                            $warnMsg[] = "Warranty card must be greater than or equal to '1' or empty!";
                        }
                        if (Str::length($LoadRate) < 0 || ! is_numeric($LoadRate) || $LoadRate < 0) {
                            $warnMsg[] = "Load rate must be greater than or equal to '0'!";
                        }
                        if (Str::length($BundleQuantity) > 0 && (! is_numeric($BundleQuantity) || $BundleQuantity <= 1)) {
                            $warnMsg[] = "Bundle quantity must be greater than or equal to '2' or empty!";
                        }
                        if (Str::length($MaterialType) > 0 && $MaterialType != '1' && $MaterialType != '2' && $MaterialType != '3' && $MaterialType != '4') { // ($this->data['material_type'] != null) &&
                            $warnMsg[] = "Material type must be '1' or '2' or '3' or '4' or empty!";
                        }

                        if (empty($warnMsg)) {
                            $recExist = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first()?->created_by;

                            if ($recExist) {
                                $createdBy = $recExist;
                            }
                        }
                    }
                }
            }
        }

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

        StickerMaster::updateOrCreate([
            'item_id' => $itemId,
            'plant_id' => $plantId,
        ],
            [
                'serial_number_motor' => $SerialNumberMotor,
                'serial_number_pump' => $SerialNumberPump,
                'serial_number_pumpset' => $SerialNumberPumpSet,
                'pack_slip_motor' => $PackSlipMotor,
                'pack_slip_pump' => $PackSlipPump,
                'pack_slip_pumpset' => $PackSlipPumpSet,
                'name_plate_motor' => $NamePlateMotor,
                'name_plate_pump' => $NamePlatePump,
                'name_plate_pumpset' => $NamePlatePumpSet,
                'tube_sticker_motor' => $TubeStickMotor,
                'tube_sticker_pump' => $TubeStickPump,
                'tube_sticker_pumpset' => $TubeStickPumpSet,
                'warranty_card' => $WarrantyCard,
                'part_validation1' => $part1,
                'part_validation2' => $part2,
                'part_validation3' => $part3,
                'part_validation4' => $part4,
                'part_validation5' => $part5,
                'laser_part_validation1' => $laserPart1,
                'laser_part_validation2' => $laserPart2,
                'panel_box_code' => $panelCod,
                'load_rate' => $LoadRate,
                'material_type' => $MaterialType,
                'bundle_quantity' => $BundleQuantity,
                'created_by' => $createdBy,
                'updated_by' => $updatedBy,
            ]);

        return null;
        // return StickerMaster::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        // return new StickerMaster();
    }

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