<?php

namespace App\Filament\Imports;

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

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->examples(['1000', '1000'])
                ->label('Plant Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('machine')
                ->requiredMapping()
                ->exampleHeader('Work Center')
                ->examples(['RMGLAS02', 'RMGLAS02'])
                ->label('Work Center')
                ->relationship(resolveUsing: 'work_center')
                ->rules(['required']),
            ImportColumn::make('approver_type')
                ->requiredMapping()
                ->exampleHeader('Approver Type')
                ->examples(['Characteristic', 'Quality'])
                ->label('Approver Type'),
            ImportColumn::make('machine_name')
                ->requiredMapping()
                ->exampleHeader('Machine Name')
                ->examples(['15002635', '17002635'])
                ->label('Machine Name'),
            ImportColumn::make('characteristic_field')
                ->requiredMapping()
                ->exampleHeader('Master Characteristic Field')
                ->examples(['NIL', 'MV SERIES'])
                ->label('Master Characteristic Field'),
            ImportColumn::make('name1')
                ->requiredMapping()
                ->exampleHeader('Approver Name 1')
                ->examples(['Test 1', 'Test 4'])
                ->label('Approver Name 1'),
            ImportColumn::make('mail1')
                ->requiredMapping()
                ->exampleHeader('Mail 1')
                ->examples(['test1@cripumps.com', 'test4@cripumps.com'])
                ->label('Mail 1'),
            ImportColumn::make('duration1')
                ->numeric()
                ->requiredMapping()
                ->exampleHeader('Duration 1')
                ->examples(['0.05', '0.30'])
                ->label('Duration 1'),
            ImportColumn::make('name2')
                ->requiredMapping()
                ->exampleHeader('Approver Name 2')
                ->examples(['Test 2', 'Test 5'])
                ->label('Approver Name 2'),
            ImportColumn::make('mail2')
                ->requiredMapping()
                ->exampleHeader('Mail 2')
                ->examples(['test2@cripumps.com', 'test5@cripumps.com'])
                ->label('Mail 2'),
            ImportColumn::make('duration2')
                ->numeric()
                ->requiredMapping()
                ->exampleHeader('Duration 2')
                ->examples(['0.05', '0.30'])
                ->label('Duration 2'),
            ImportColumn::make('name3')
                ->requiredMapping()
                ->exampleHeader('Approver Name 3')
                ->examples(['Test 3', 'Test 6'])
                ->label('Approver Name 3'),
            ImportColumn::make('mail3')
                ->requiredMapping()
                ->exampleHeader('Mail 3')
                ->examples(['test3@cripumps.com', 'test6@cripumps.com'])
                ->label('Mail 3'),
            ImportColumn::make('duration3')
                ->numeric()
                ->requiredMapping()
                ->exampleHeader('Duration 3')
                ->examples(['0.05', '0.30'])
                ->label('Duration 3'),
        ];
    }

    public function resolveRecord(): ?CharacteristicApproverMaster
    {
        // return CharacteristicApproverMaster::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        $warnMsg = [];
        $plantCod = trim($this->data['plant']) ?? null;
        $workCenter = trim($this->data['machine']) ?? null;
        $apprTyp = trim($this->data['approver_type']) ?? null;
        $machineNam = trim($this->data['machine_name']) ?? null;
        $mastCharFld = trim($this->data['characteristic_field']) ?? null; // zmm_pumpseries
        $apprNam1 = trim($this->data['name1']) ?? null;
        $apprMail1 = trim($this->data['mail1']) ?? null;
        $apprDur1 = trim($this->data['duration1']) ?? 0.01;
        $apprNam2 = trim($this->data['name2']) ?? null;
        $apprMail2 = trim($this->data['mail2']) ?? null;
        $apprDur2 = trim($this->data['duration2']) ?? 0.01;
        $apprNam3 = trim($this->data['name3']) ?? null;
        $apprMail3 = trim($this->data['mail3']) ?? null;
        $apprDur3 = trim($this->data['duration3']) ?? 0.01;
        $createdBy = Filament::auth()->user()->name;
        $updatedBy = $createdBy;

        $plantId = null;
        $machineId = null;

        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 ($workCenter == null || $workCenter == '') {
            $warnMsg[] = "Work center can't be empty!";
        }
        if ($apprTyp == '' || $apprTyp == null || ($apprTyp != 'Characteristic' && $apprTyp != 'Quality')) {
            $warnMsg[] = "Approver type must be either 'Characteristic' or 'Quality'!";
        }
        if ($machineNam == null || $machineNam == '') {
            $warnMsg[] = "Machine name can't be empty!";
        }
        if ($mastCharFld == null || $mastCharFld == '') {
            $mastCharFld = 'NIL';
        }
        if ($apprNam1 == null || $apprNam1 == '') {
            $warnMsg[] = "Approver name 1 can't be empty!";
        }
        if ($apprMail1 == null || $apprMail1 == '') {
            $warnMsg[] = "Approver email 1 can't be empty!";
        }
        if (! is_numeric($apprDur1)) {
            $warnMsg[] = 'Duration 1 must be a numeric value (HH.MM)!';
        }
        if ($apprDur2 != null && $apprDur2 != '' && ! is_numeric($apprDur2)) {
            $warnMsg[] = 'Duration 2 must be a numeric value (HH.MM)!';
        }
        if ($apprDur3 != null && $apprDur3 != '' && ! is_numeric($apprDur3)) {
            $warnMsg[] = 'Duration 3 must be a numeric value (HH.MM)!';
        }

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

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

            $machine = Machine::where('work_center', $workCenter)->first();
            if (! $machine) {
                $warnMsg[] = 'Work center not found!';
            } else {
                $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

                if (! $machine) {
                    $warnMsg[] = 'Work center not found for the given plant!';
                } else {
                    $machineId = $machine->id;
                }
            }

            $getCreatedBy = CharacteristicApproverMaster::where('plant_id', $plantId)
                ->where('machine_id', $machineId)
                ->where('approver_type', $apprTyp)
                ->where('machine_name', $machineNam)
                ->where('characteristic_field', $mastCharFld)
                ->first()?->created_by;

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

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

        CharacteristicApproverMaster::updateOrCreate(
            [
                'plant_id' => $plantId,
                'machine_id' => $machineId,
                'approver_type' => $apprTyp,
                'machine_name' => $machineNam,
                'characteristic_field' => $mastCharFld,
            ],
            [
                'name1' => $apprNam1,
                'mail1' => $apprMail1,
                'duration1' => $apprDur1,
                'name2' => $apprNam2,
                'mail2' => $apprMail2,
                'duration2' => $apprDur2,
                'name3' => $apprNam3,
                'mail3' => $apprMail3,
                'duration3' => $apprDur3,
                'created_by' => $createdBy,
                'updated_by' => $updatedBy,
            ]);

        return null;

        // return new CharacteristicApproverMaster;
    }

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