<?php

namespace App\Filament\Imports;

use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\QualityValidation;
use App\Models\StickerMaster;
use App\Models\User;
use Carbon\Carbon;
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 QualityValidationImporter extends Importer
{
    protected static ?string $model = QualityValidation::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('created_at')
                ->requiredMapping()
                ->exampleHeader('Created DateTime')
                ->example('12-02-2025 15:51:00')
                ->label('Created DateTime')
                ->rules(['required']),
            ImportColumn::make('sticker_master_id_code') // stickerMaster.item
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example('123456')
                ->label('Item Code'),
            // ->relationship(
            //     name: 'stickerMaster',
            //     resolveUsing: function ($state) {
            //         $state = trim($state);
            //         $item = Item::where('code', $state)->first();
            //         return $item
            //             ? StickerMaster::where('item_id', $item->id)->value('id')
            //             : null;
            //     }
            // ),
            ImportColumn::make('production_order')
                ->requiredMapping()
                ->exampleHeader('Production Order')
                ->example('1234567')
                ->label('Production Order')
                ->rules(['required']),
            ImportColumn::make('serial_number')
                ->requiredMapping()
                ->exampleHeader('Serial Number')
                ->example('1234567890123')
                ->label('Serial Number'),
            ImportColumn::make('serial_number_motor')
                ->requiredMapping()
                ->exampleHeader('Serial Number Motor')
                ->example('1')
                ->label('Serial Number Motor'),
            ImportColumn::make('serial_number_pump')
                ->requiredMapping()
                ->exampleHeader('Serial Number Pump')
                ->example('1')
                ->label('Serial Number Pump'),
            ImportColumn::make('serial_number_pumpset')
                ->requiredMapping()
                ->exampleHeader('Serial Number PumpSet')
                ->example('1')
                ->label('Serial Number PumpSet'),
            ImportColumn::make('pack_slip_motor')
                ->requiredMapping()
                ->exampleHeader('Pack Slip Motor')
                ->example('1')
                ->label('Pack Slip Motor'),
            ImportColumn::make('pack_slip_pump')
                ->requiredMapping()
                ->exampleHeader('Pack Slip Pump')
                ->example('1')
                ->label('Pack Slip Pump'),
            ImportColumn::make('pack_slip_pumpset')
                ->requiredMapping()
                ->exampleHeader('Pack Slip PumpSet')
                ->example('1')
                ->label('Pack Slip PumpSet'),
            ImportColumn::make('name_plate_motor')
                ->requiredMapping()
                ->exampleHeader('Name Plate Motor')
                ->example('1')
                ->label('Name Plate Motor'),
            ImportColumn::make('name_plate_pump')
                ->requiredMapping()
                ->exampleHeader('Name Plate Pump')
                ->example('1')
                ->label('Name Plate Pump'),
            ImportColumn::make('name_plate_pumpset')
                ->requiredMapping()
                ->exampleHeader('Name Plate PumpSet')
                ->example('1')
                ->label('Name Plate PumpSet'),
            ImportColumn::make('warranty_card')
                ->requiredMapping()
                ->exampleHeader('Warranty Card')
                ->example('1')
                ->label('Warranty Card'),
            ImportColumn::make('tube_sticker_motor')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker Motor')
                ->example('1')
                ->label('Tube Sticker Motor'),
            ImportColumn::make('tube_sticker_pump')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker Pump')
                ->example('1')
                ->label('Tube Sticker Pump'),
            ImportColumn::make('tube_sticker_pumpset')
                ->requiredMapping()
                ->exampleHeader('Tube Sticker PumpSet')
                ->example('1')
                ->label('Tube Sticker PumpSet'),
            ImportColumn::make('part_validation1')
                ->requiredMapping()
                ->exampleHeader('Part Validation 1')
                ->example('12345')
                ->label('Part Validation 1'),
            ImportColumn::make('part_validation2')
                ->requiredMapping()
                ->exampleHeader('Part Validation 2')
                ->example('54321')
                ->label('Part Validation 2'),
            ImportColumn::make('part_validation3')
                ->requiredMapping()
                ->exampleHeader('Part Validation 3')
                ->example('12345')
                ->label('Part Validation 3'),
            ImportColumn::make('part_validation4')
                ->requiredMapping()
                ->exampleHeader('Part Validation 4')
                ->example('')
                ->label('Part Validation 4'),
            ImportColumn::make('part_validation5')
                ->requiredMapping()
                ->exampleHeader('Part Validation 5')
                ->example('')
                ->label('Part Validation 5'),
            ImportColumn::make('uom')
                ->requiredMapping()
                ->exampleHeader('Unit of Measure')
                ->example('EA')
                ->label('Unit of Measure'),
            ImportColumn::make('line')
                ->requiredMapping()
                ->exampleHeader('Line Name')
                ->example('4 inch pump line')
                ->label('Line Name')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('Plant Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('updated_at')
                ->requiredMapping()
                ->exampleHeader('Updated DateTime')
                ->example('12-02-2025 15:51:00')
                ->label('Updated DateTime')
                ->rules(['required']),
            ImportColumn::make('operator_id')
                ->requiredMapping()
                ->exampleHeader('Operator ID')
                ->example(Filament::auth()->user()->name)
                ->label('Operator ID')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?QualityValidation
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $line = null;
        $stickMaster = 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';
        } else {
            $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
            $uniqueCode = trim($this->data['sticker_master_id_code']); // stickerMaster.item
            $stickMaster = StickerMaster::select('id')->with('item')
                ->whereHas('item', function ($query) use ($uniqueCode, $plant) {
                    $query->where('code', $uniqueCode)->where('plant_id', $plant->id);
                })->value('id');
        }

        if (! $line) {
            $warnMsg[] = 'Line not found';
        }

        if (! $stickMaster) {
            $warnMsg[] = 'Sticker item code not found';
        }

        if (! is_numeric($this->data['production_order']) || Str::length($this->data['production_order']) < 7 || Str::length($this->data['production_order']) > 14) {
            $warnMsg[] = 'Invalid production order found';
        }

        if (! ctype_alnum($this->data['serial_number']) || Str::length($this->data['serial_number']) < 9) {
            $warnMsg[] = 'Invalid serial number found';
        }
        // dd($stickMaster);

        // if (Str::length($this->data['uom']) < 1) {
        //     $warnMsg[] = "Invalid unit of measure found";
        // }

        $user = User::where('name', $this->data['operator_id'])->first();
        if (! $user) {
            $warnMsg[] = 'Operator ID not found';
        }
        $fromDate = $this->data['created_at'];
        $toDate = $this->data['updated_at'];

        $formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00'

        $fdateTime = null;
        $tdateTime = null;
        // Try parsing with multiple formats
        foreach ($formats as $format) {
            try {
                $fdateTime = Carbon::createFromFormat($format, $fromDate);
                break;
            } catch (\Exception $e) {
                // Optionally collect warning messages
                // $warnMsg[] = "Date format mismatch with format: $format";
            }
        }

        foreach ($formats as $format) {
            try {
                $tdateTime = Carbon::createFromFormat($format, $toDate);
                break;
            } catch (\Exception $e) {
                // Optionally collect warning messages
                // $warnMsg[] = "Date format mismatch with format: $format";
            }
        }

        // $fDateOnly = '';
        if (! isset($fdateTime)) {
            // throw new \Exception('Invalid date time format');
            $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
        }
        // else {
        //     $fDateOnly = $fdateTime->toDateString();
        // }
        if (! isset($tdateTime)) {
            $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
        }

        if (isset($fdateTime) && isset($tdateTime)) {
            if ($fdateTime->greaterThan($tdateTime)) {
                $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'.";
            }
        }
        // if (!$fromDate) {
        //     $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
        // }
        // else if (!$toDate) {
        //     $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
        // }

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

        QualityValidation::updateOrCreate([
            'plant_id' => $plant->id,
            'sticker_master_id' => $stickMaster, // ->id
            'serial_number' => $this->data['serial_number'],
        ],
            [
                'line_id' => $line->id,
                'uom' => $this->data['uom'],
                'production_order' => $this->data['production_order'],
                'serial_number_motor' => $this->data['serial_number_motor'],
                'serial_number_pump' => $this->data['serial_number_pump'],
                'serial_number_pumpset' => $this->data['serial_number_pumpset'],
                'pack_slip_motor' => $this->data['pack_slip_motor'],
                'pack_slip_pump' => $this->data['pack_slip_pump'],
                'pack_slip_pumpset' => $this->data['pack_slip_pumpset'],
                'name_plate_motor' => $this->data['name_plate_motor'],
                'name_plate_pump' => $this->data['name_plate_pump'],
                'name_plate_pumpset' => $this->data['name_plate_pumpset'],
                'tube_sticker_motor' => $this->data['tube_sticker_motor'],
                'tube_sticker_pump' => $this->data['tube_sticker_pump'],
                'tube_sticker_pumpset' => $this->data['tube_sticker_pumpset'],
                'warranty_card' => $this->data['warranty_card'],
                'part_validation1' => $this->data['part_validation1'],
                'part_validation2' => $this->data['part_validation2'],
                'part_validation3' => $this->data['part_validation3'],
                'part_validation4' => $this->data['part_validation4'],
                'part_validation5' => $this->data['part_validation5'],
                'created_at' => $fdateTime->format('Y-m-d H:i:s'), // $this->data['created_at'],
                'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'],
                'operator_id' => $this->data['operator_id'],
            ]);

        return null;
        // return QualityValidation::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        // return new QualityValidation();
    }

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