<?php

namespace App\Filament\Imports;

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

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('PLANT CODE')
                ->example('1200')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('line')
                ->exampleHeader('LINE NAME')
                ->example('Poly Wrapped Wire SFG')
                ->label('LINE NAME')
                ->relationship(resolveUsing: 'name'),
            ImportColumn::make('item')
                ->requiredMapping()
                ->exampleHeader('ITEM CODE')
                ->example('123456')
                ->label('ITEM CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('machine_name')
                ->requiredMapping()
                ->exampleHeader('MACHINE NAME')
                ->example('RMI001234')
                ->label('MACHINE NAME')
                // ->relationship(resolveUsing: 'work_center')
                ->rules(['required']),
            ImportColumn::make('production_order')
                ->requiredMapping()
                ->exampleHeader('PRODUCTION ORDER')
                ->example('1880231')
                ->label('PRODUCTION ORDER')
                ->rules(['required']),
            ImportColumn::make('serial_number')
                ->requiredMapping()
                ->exampleHeader('SERIAL NUMBER')
                ->example('20001202121')
                ->label('SERIAL NUMBER')
                ->rules(['required']),
            ImportColumn::make('characteristic_name')
                ->requiredMapping()
                ->exampleHeader('CHARACTERISTIC NAME')
                ->example('Voltage')
                ->label('CHARACTERISTIC NAME'),
            ImportColumn::make('observed_value')
                ->exampleHeader('OBSERVED VALUE')
                ->example('0')
                ->label('OBSERVED VALUE'),
            ImportColumn::make('status')
                ->exampleHeader('STATUS')
                ->example('Ok')
                ->label('STATUS'),
            ImportColumn::make('remark')
                ->exampleHeader('REMARK')
                ->example('Issue')
                ->label('REMARK'),
        ];
    }

    public function resolveRecord(): ?ProductionCharacteristic
    {

        $warnMsg = [];
        $plant = null;
        $plantCod = trim($this->data['plant']) ?? '';
        $plantId = null;
        $iCode = trim($this->data['item']) ?? '';
        $itemId = null;
        $lineNam = trim($this->data['line']) ?? '';
        $lineId = null;
        $machineName = trim($this->data['machine_name'] ?? '');
        $pOrder = trim($this->data['production_order'] ?? '');
        $sNo = trim($this->data['serial_number'] ?? '');
        $charName = trim($this->data['characteristic_name'] ?? '');
        $obsValue = trim($this->data['observed_value'] ?? '');
        $status = trim($this->data['status'] ?? '');
        $remark = trim($this->data['remark'] ?? '');

        if ($plantCod == null || $plantCod == '') {
            $warnMsg[] = "Plant code can't be empty!";
        } elseif (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
            $warnMsg[] = 'Invalid plant code found';
        }
        if ($iCode == null || $iCode == '') {
            $warnMsg[] = "Item code can't be empty!";
        } elseif (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
            $warnMsg[] = 'Invalid item code found!';
        }
        if ($machineName != null && $machineName != '' && Str::length($machineName) > 18) {
            $warnMsg[] = 'Invalid machine name found!';
        }

        $plant = Plant::where('code', $plantCod)->first();
        if (! $plant) {
            $warnMsg[] = 'Plant not found!';
        } else {
            $plantId = $plant->id;
        }

        $itemCode = Item::where('code', $iCode)->first();
        if (! $itemCode) {
            $warnMsg[] = 'Item code not found!';
        } else {
            if ($plantId) {
                $itemCode = Item::where('code', $iCode)->where('plant_id', $plantId)->first();
                if (! $itemCode) {
                    $warnMsg[] = 'Item code not found for the given plant!';
                } else {
                    $itemId = $itemCode->id;
                }
            }
        }

        $lineExists = Line::where('name', $lineNam)->first();
        if (! $lineExists) {
            $warnMsg[] = 'Line name not found!';
        } else {
            if ($plantId) {
                $lineAgainstPlant = Line::where('name', $lineNam)->where('plant_id', $plantId)->first();
                if (! $lineAgainstPlant) {
                    $warnMsg[] = 'Line name not found for the given plant!';
                } else {
                    $lineId = $lineAgainstPlant->id;
                }
            }
        }

        $machineExists = Machine::where('work_center', $machineName)->first();
        if (! $machineExists) {
            $warnMsg[] = 'Machine not found!';
        } else {
            if ($plantId) {
                $machineAgainstPlant = Machine::where('work_center', $machineName)->where('plant_id', $plantId)->first();
                if (! $machineAgainstPlant) {
                    $warnMsg[] = 'Machine not found for the given plant!';
                } else {
                    $machineId = $machineAgainstPlant->id;
                }
            }
        }

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

        ProductionCharacteristic::Create(
            [
                'plant_id' => $plantId,
                'line_id' => $lineId,
                'item_id' => $itemId,
                'machine_id' => $machineId,
                'production_order' => $pOrder,
                'serial_number' => $sNo,
                'characteristic_name' => $charName,
                'observed_value' => $obsValue,
                'status' => $status,
                'remark' => $remark,
                'created_at' => now(),
                'updated_at' => now(),
                'created_by' => Filament::auth()->user()->name,
                'updated_by' => Filament::auth()->user()->name,
            ]
        );

        return null;

        // return new ProductionCharacteristic();
    }

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