<?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 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 Name')
                ->example('Ransar Industries-I')
                ->label('PLANT NAME')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?StickerMaster
    {
        $warnMsg = [];
        $item = null;
        $plant = Plant::where('name', $this->data['plant'])->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 code not found";
            }
            else
            {
                if (Str::length($this->data['serial_number_motor']) > 0 && $this->data['serial_number_motor'] != '1') {
                    $warnMsg[] = "Serial number motor must be 1 or empty";
                }
                if (Str::length($this->data['serial_number_pump']) > 0 && $this->data['serial_number_pump'] != '1') {
                    $warnMsg[] = "Serial number pump must be 1 or empty";
                }
                if (Str::length($this->data['serial_number_pumpset']) > 0 && $this->data['serial_number_pumpset'] != '1') {
                    $warnMsg[] = "Serial number pumpset must be 1 or empty";
                }
                if (Str::length($this->data['pack_slip_motor']) > 0 && $this->data['pack_slip_motor'] != '1') {
                    $warnMsg[] = "Pack slip motor must be 1 or empty";
                }
                if (Str::length($this->data['pack_slip_pump']) > 0 && $this->data['pack_slip_pump'] != '1') {
                    $warnMsg[] = "Pack slip pump must be 1 or empty";
                }
                if (Str::length($this->data['pack_slip_pumpset']) > 0 && $this->data['pack_slip_pumpset'] != '1') {
                    $warnMsg[] = "Pack slip pumpset must be 1 or empty";
                }
                if (Str::length($this->data['name_plate_motor']) > 0 && $this->data['name_plate_motor'] != '1') {
                    $warnMsg[] = "Name plate motor must be 1 or empty";
                }
                if (Str::length($this->data['name_plate_pump']) > 0 && $this->data['name_plate_pump'] != '1') {
                    $warnMsg[] = "Name plate pump must be 1 or empty";
                }
                if (Str::length($this->data['name_plate_pumpset']) > 0 && $this->data['name_plate_pumpset'] != '1') {
                    $warnMsg[] = "Name plate pumpset must be 1 or empty";
                }
                if (Str::length($this->data['tube_sticker_motor']) > 0 && $this->data['tube_sticker_motor'] != '1') {
                    $warnMsg[] = "Tube sticker motor must be 1 or empty";
                }
                if (Str::length($this->data['tube_sticker_pump']) > 0 && $this->data['tube_sticker_pump'] != '1') {
                    $warnMsg[] = "Tube sticker pump must be 1 or empty";
                }
                if (Str::length($this->data['tube_sticker_pumpset']) > 0 && $this->data['tube_sticker_pumpset'] != '1') {
                    $warnMsg[] = "Tube sticker pumpset must be 1 or empty";
                }
                if (Str::length($this->data['warranty_card']) > 0 && $this->data['warranty_card'] != '1') {
                    $warnMsg[] = "Warranty card must be 1 or empty";
                }
                if (Str::length($this->data['panel_box_code']) > 0 && (Str::length($this->data['panel_box_code']) < 6 || !ctype_alnum($this->data['panel_box_code']))) {
                    $warnMsg[] = "Invalid panel box code found";
                }
                if (Str::length($this->data['load_rate']) < 0 || !is_numeric($this->data['load_rate']) || $this->data['load_rate'] < 0) {
                    $warnMsg[] = "Load rate must be greater than or equal to 0";
                }
                if (Str::length($this->data['bundle_quantity']) > 0 && (!is_numeric($this->data['bundle_quantity']) || $this->data['bundle_quantity'] <= 1)) {
                    $warnMsg[] = "Bundle quantity must be greater than or equal to '2' or empty";
                }
                if (Str::length($this->data['material_type']) > 0 && $this->data['material_type'] != '1' && $this->data['material_type'] != '2' && $this->data['material_type'] != '3') { //($this->data['material_type'] != null) &&
                    $warnMsg[] = "Material type must be 1 or 2 or 3 or empty";
                }
            }
        }

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

        StickerMaster::updateOrCreate([
            'item_id' => $item->id,
            'plant_id' => $plant->id
        ],
        [
            'serial_number_motor' => $this->data['serial_number_motor'],
            'serial_number_pump' => $this->data['serial_number_pump'],
            'serial_number_pumpset' => $this->data['serial_number_pumpset'],
            'pack_slip_motor' => $this->data['pack_slip_motor'],
            'pack_slip_pump' => $this->data['pack_slip_pump'],
            'pack_slip_pumpset' => $this->data['pack_slip_pumpset'],
            'name_plate_motor' => $this->data['name_plate_motor'],
            'name_plate_pump' => $this->data['name_plate_pump'],
            'name_plate_pumpset' => $this->data['name_plate_pumpset'],
            'tube_sticker_motor' => $this->data['tube_sticker_motor'],
            'tube_sticker_pump' => $this->data['tube_sticker_pump'],
            'tube_sticker_pumpset' => $this->data['tube_sticker_pumpset'],
            'warranty_card' => $this->data['warranty_card'],
            'part_validation1' => $this->data['part_validation1'],
            'part_validation2' => $this->data['part_validation2'],
            'part_validation3' => $this->data['part_validation3'],
            'part_validation4' => $this->data['part_validation4'],
            'part_validation5' => $this->data['part_validation5'],
            'laser_part_validation1' => $this->data['laser_part_validation1'],
            'laser_part_validation2' => $this->data['laser_part_validation2'],
            'panel_box_code' => $this->data['panel_box_code'],
            'load_rate' => $this->data['load_rate'],
            'bundle_quantity' => $this->data['bundle_quantity'],
            'material_type' => $this->data['material_type']
        ]);
        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;
    }
}
