<?php

namespace App\Filament\Imports;

use App\Models\Locator;
use App\Models\PalletValidation;
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 Filament\Facades\Filament;
use Str;

class LocatorImporter extends Importer
{
    protected static ?string $model = Locator::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('locator_number')
                ->requiredMapping()
                ->exampleHeader('Locator Number')
                ->example(['W01-A1A'])
                ->label('Locator Number')
                ->rules(['required']),
            ImportColumn::make('locator_quantity')
                ->requiredMapping()
                ->numeric()
                ->exampleHeader('Locator Quantity')
                ->example(['0'])
                ->label('Locator Quantity')
                ->rules(['required', 'integer']),
            ImportColumn::make('operator_id')
                ->requiredMapping()
                ->exampleHeader('Operator ID')
                ->example(['Admin'])
                ->label('Operator ID')
                ->rules(['required']),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->relationship(resolveUsing: 'code')
                ->exampleHeader('Plant Code')
                ->example(['1000'])
                ->label('Plant Code')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?Locator
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $user = null;
        $locator = $this->data['locator_number'];
        // $locatorQuantity = $this->data['locator_quantity'];
        $palletQuantity = 0;
        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
            {
                $user = Filament::auth()->user()->name;
                if (Str::length($locator) < 7) {
                    $warnMsg[] = "Invalid locator number found";
                }
                else {
                    // $locat = Locator::where('name', $locator)->where('plant_id', $plant->id)->first();
                    $palletQuantity = PalletValidation::where('locator_number', $locator)->where('plant_id', $plant->id)->distinct('pallet_number')->count('pallet_number');
                }
            }
        }

        // if (Str::length($locatorQuantity) < 0 || !is_numeric($locatorQuantity) || $locatorQuantity < 0 || $locatorQuantity > 2) {
        //     $warnMsg[] = "Invalid locator quantity found";
        // }

        // $user = User::where('name', $user)->first();
        // if (!$user) {
        //     $warnMsg[] = "Operator ID not found";
        // }

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

        Locator::updateOrCreate(
            [
                'plant_id' => $plant->id,
                'locator_number' => $locator
            ],
            [
                'locator_quantity' => $palletQuantity,
                'operator_id' => $user
            ]
        );
        return null;
        // // return Locator::firstOrNew([
        // //     // Update existing records, matching them by `$this->data['column_name']`
        // //     'email' => $this->data['email'],
        // // ]);

        // return new Locator();
    }

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