<?php

namespace App\Filament\Imports;

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

class PanelGrMasterImporter extends Importer
{
    protected static ?string $model = PanelGrMaster::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('item')
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example('630214')
                ->label('Item Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('document_number')
                ->requiredMapping()
                ->exampleHeader('Document Number')
                ->example('11023567')
                ->label('Document Number')
                ->rules(['required']),
            ImportColumn::make('invoice_number')
                ->requiredMapping()
                ->exampleHeader('Invoice Number')
                ->example('3RAW0012345')
                ->label('Invoice Number')
                ->rules(['required']),
            ImportColumn::make('supplier_number')
                ->requiredMapping()
                ->exampleHeader('Supplier Number')
                ->example('154564564')
                ->label('Supplier Number')
                ->rules(['required']),
            ImportColumn::make('inspection_lot_number')
                ->requiredMapping()
                ->exampleHeader('Inspection Lot Number')
                ->example('154564564')
                ->label('Inspection Lot Number')
                ->rules(['required']),
            ImportColumn::make('quantity')
                ->requiredMapping()
                ->exampleHeader('Quantity')
                ->example('10')
                ->label('Quantity')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?PanelGrMaster
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $item = null;
        $userName = Filament::auth()->user()?->name;

        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 {
                $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first();
            }
            if (! $item) {
                $warnMsg[] = 'Item not found';
            }
        }

        if (empty($this->data['document_number'])) {
            $warnMsg[] = 'Document Number cannot be empty.';
        }

        // if (Str::length($this->data['invoice_number']) < 7 || ! ctype_alnum($this->data['invoice_number'])) {
        //     $warnMsg[] = 'Invalid invoice number found';
        // }

        if (empty($this->data['supplier_number'])) {
            $warnMsg[] = 'Supplier Number cannot be empty.';
        }

        if (empty($this->data['inspection_lot_number'])) {
            $warnMsg[] = 'Inspection Lot Number cannot be empty.';
        }
        if (!is_numeric($this->data['inspection_lot_number'])) {
            $warnMsg[] = 'Inspection Lot Number must be a valid number.';
        }

        if (empty($this->data['quantity'])) {
            $warnMsg[] = 'Quantity cannot be empty.';
        }
        elseif (!is_numeric($this->data['quantity'])) {
            $warnMsg[] = 'Quantity must be a valid number.';
        } elseif ((float) $this->data['quantity'] <= 0) {
            $warnMsg[] = 'Quantity must be greater than 0.';
        }

        $existingRecord = PanelGrMaster::where('document_number', $this->data['document_number'])->where('plant_id', $this->data['plant'])->first();

        if ($existingRecord && $existingRecord->invoice_number != $this->data['invoice_number'])
        {
            $warnMsg[] = "Document Number '{$this->data['document_number']}' is already associated with Invoice Number '{$existingRecord->invoice_number}'.";
        }

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

        PanelGrMaster::updateOrCreate(
            [
                'plant_id' => $plant->id,
                'item_id' => $item->id,
                'document_number' => $this->data['document_number'],
                'invoice_number' => $this->data['invoice_number'],
                'supplier_number' => $this->data['supplier_number'] ?? null,
                'inspection_lot_number' => $this->data['inspection_lot_number'] ?? null,
            ],
            [
                'quantity' => $this->data['quantity'] ?? null,
                'updated_by' => $userName,
                'created_by' => $userName, // Only used when creating
            ]
        );

        return null;
        // return new PanelGrMaster();
    }

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