<?php

namespace App\Filament\Imports;

use App\Models\CheckPointName;
use App\Models\CheckPointTime;
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 CheckPointTimeImporter extends Importer
{
    protected static ?string $model = CheckPointTime::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('checkPointNames1')
                ->requiredMapping()
                ->exampleHeader('Check Point 1')
                ->example('STP BACKSIDE')
                ->label('Check Point 1')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
            ImportColumn::make('checkPointNames2')
                ->requiredMapping()
                ->exampleHeader('Check Point 2')
                ->example('CANTEEN')
                ->label('Check Point 2')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
            ImportColumn::make('sequence_number')
                ->requiredMapping()
                ->exampleHeader('Sequence Number')
                ->example('1')
                ->label('Sequence Number')
                ->integer()
                ->rules(['required']),
            ImportColumn::make('time_lapse')
                ->requiredMapping()
                ->exampleHeader('Time Lapse')
                ->example('1')
                ->label('Time Lapse')
                ->integer()
                ->rules(['required']),
            ImportColumn::make('time_lapse_cushioning')
                ->requiredMapping()
                ->exampleHeader('Time Lapse Cushioning')
                ->example('1')
                ->label('Time Lapse Cushioning')
                ->integer()
                ->rules(['required']),
            ImportColumn::make('created_by')
                ->requiredMapping()
                ->exampleHeader('Created By')
                ->example(Filament::auth()->user()->name ?? 'Admin')
                ->label('Created By')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?CheckPointTime
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $checkPointNames1 = null;
        $checkPointNames2 = null;
        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'; // '" . $plantCod . "'
            } else {
                $checkPointNames1 = CheckPointName::where('name', $this->data['checkPointNames1'])->first();
                if (! $checkPointNames1) {
                    $warnMsg[] = 'Check point 1 not found';
                } else {
                    $checkPointNames2 = CheckPointName::where('name', $this->data['checkPointNames2'])->first();
                    if (! $checkPointNames2) {
                        $warnMsg[] = 'Check point 2 not found';
                    } else {
                        if ($checkPointNames1->id === $checkPointNames2->id) {
                            $warnMsg[] = "Check point 1 and 2 can't be the same";
                        }
                    }
                }
            }
        }

        if (Str::length($this->data['sequence_number']) < 1 || ! is_numeric($this->data['sequence_number']) || $this->data['sequence_number'] <= 0) {
            $warnMsg[] = 'Invalid sequence number found';
        }

        if (Str::length($this->data['time_lapse']) < 1 || ! is_numeric($this->data['time_lapse']) || $this->data['time_lapse'] <= 0) {
            $warnMsg[] = 'Invalid time lapse found';
        }

        if (Str::length($this->data['time_lapse_cushioning']) < 1 || ! is_numeric($this->data['time_lapse_cushioning']) || $this->data['time_lapse_cushioning'] <= 0) {
            $warnMsg[] = 'Invalid time lapse cushioning found';
        }

        $createdBy = $this->data['created_by'];
        if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy)
            $warnMsg[] = 'Invalid created by name found';
        }

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

        return CheckPointTime::updateOrCreate([
            'plant_id' => $plant->id,
            'check_point1_id' => $checkPointNames1->id,
            'check_point2_id' => $checkPointNames2->id,
            'sequence_number' => $this->data['sequence_number'],
        ],
            [
                'time_lapse' => $this->data['time_lapse'],
                'time_lapse_cushioning' => $this->data['time_lapse_cushioning'],
                'created_by' => $this->data['created_by'],
            ]
        );
        // // return CheckPointTime::firstOrNew([
        // //     // Update existing records, matching them by `$this->data['column_name']`
        // //     'email' => $this->data['email'],
        // // ]);

        // return new CheckPointTime();
    }

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