<?php

namespace App\Filament\Imports;

use App\Models\Plant;
use App\Models\StickerDetail;
use App\Models\StickerStructureDetail;
use App\Models\User;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;

class StickerDetailImporter extends Importer
{
    protected static ?string $model = StickerDetail::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('sticker_structure_detail_id')
                ->requiredMapping()
                ->exampleHeader('Sticker ID')
                ->example('123456')
                ->label('STICKER ID')
                ->rules(['required']),
            ImportColumn::make('design_element_type')
                ->requiredMapping()
                ->exampleHeader('Design Element Type')
                ->label('DESIGN ELEMENT TYPE')
                ->example('Text/Shape/Image/QR'),
            ImportColumn::make('element_id')
                ->requiredMapping()
                ->exampleHeader('Element ID')
                ->label('ELEMENT ID')
                ->example('001'),
            ImportColumn::make('element_type')
                ->requiredMapping()
                ->exampleHeader('Element Type')
                ->label('ELEMENT TYPE')
                ->example('Static/Dynamic'),
            ImportColumn::make('characteristics_type')
                ->requiredMapping()
                ->exampleHeader('Characteristics Type')
                ->label('CHARACTERISTICS TYPE')
                ->example('ZMM values'),
            ImportColumn::make('string_value')
                ->requiredMapping()
                ->exampleHeader('String Value')
                ->label('STRING VALUE')
                ->example('1'),
            ImportColumn::make('string_font')
                ->requiredMapping()
                ->exampleHeader('String Font')
                ->label('STRING FONT')
                ->example('Arial'),
            ImportColumn::make('string_size')
                ->requiredMapping()
                ->exampleHeader('String Size')
                ->label('STRING SIZE')
                ->example('12'),
            ImportColumn::make('element_colour')
                ->requiredMapping()
                ->exampleHeader('Element Colour')
                ->label('ELEMENT COLOUR')
                ->example('Black'),
            ImportColumn::make('string_align')
                ->requiredMapping()
                ->exampleHeader('String Align')
                ->label('STRING ALIGN')
                ->example('Left/Center/Right'),
            ImportColumn::make('string_x_value')
                ->requiredMapping()
                ->exampleHeader('String X Value')
                ->label('STRING X VALUE')
                ->example('10'),
            ImportColumn::make('string_y_value')
                ->requiredMapping()
                ->exampleHeader('String Y Value')
                ->label('STRING Y VALUE')
                ->example('20'),
            ImportColumn::make('shape_name')
                ->requiredMapping()
                ->exampleHeader('Shape Name')
                ->label('SHAPE NAME')
                ->example('Line/Rectangle/CurvedRectangle'),
            ImportColumn::make('shape_pen_size')
                ->requiredMapping()
                ->exampleHeader('Shape Pen Size')
                ->label('SHAPE PEN SIZE')
                ->example('0.3'),
            ImportColumn::make('curve_radius')
                ->requiredMapping()
                ->exampleHeader('Curve Radius')
                ->label('CURVE RADIUS')
                ->example('3'),
            ImportColumn::make('shape_x1_value')
                ->requiredMapping()
                ->exampleHeader('Shape X1 Value')
                ->label('SHAPE X1 VALUE')
                ->example('10'),
            ImportColumn::make('shape_y1_value')
                ->requiredMapping()
                ->exampleHeader('Shape Y1 Value')
                ->label('SHAPE Y1 VALUE')
                ->example('20'),
            ImportColumn::make('shape_x2_value')
                ->requiredMapping()
                ->exampleHeader('Shape X2 Value')
                ->label('SHAPE X2 VALUE')
                ->example('30'),
            ImportColumn::make('shape_y2_value')
                ->requiredMapping()
                ->exampleHeader('Shape Y2 Value')
                ->label('SHAPE Y2 VALUE')
                ->example('40'),
            ImportColumn::make('image_x')
                ->requiredMapping()
                ->exampleHeader('Image X')
                ->label('IMAGE X')
                ->example('15'),
            ImportColumn::make('image_y')
                ->requiredMapping()
                ->exampleHeader('Image Y')
                ->label('IMAGE Y')
                ->example('25'),
            ImportColumn::make('image_width')
                ->requiredMapping()
                ->exampleHeader('Image Width')
                ->label('IMAGE WIDTH')
                ->example('100'),
            ImportColumn::make('image_height')
                ->requiredMapping()
                ->exampleHeader('Image Height')
                ->label('IMAGE HEIGHT')
                ->example('100'),
            ImportColumn::make('qr_value')
                ->requiredMapping()
                ->exampleHeader('QR Value')
                ->label('QR VALUE')
                ->example('246118|53246735267'),
            ImportColumn::make('qr_align')
                ->requiredMapping()
                ->exampleHeader('QR Align')
                ->label('QR ALIGN')
                ->example('Left/Center/Right'),
            ImportColumn::make('qr_size')
                ->requiredMapping()
                ->exampleHeader('QR Size')
                ->label('QR SIZE')
                ->example('10'),
            ImportColumn::make('qr_x_value')
                ->requiredMapping()
                ->exampleHeader('QR X Value')
                ->label('QR X VALUE')
                ->example('30'),
            ImportColumn::make('qr_y_value')
                ->requiredMapping()
                ->exampleHeader('QR Y Value')
                ->label('QR Y VALUE')
                ->example('40'),
            ImportColumn::make('created_by')
                ->requiredMapping()
                ->exampleHeader('Created By')
                ->label('CREATED BY')
                ->example('RAW001234'),
        ];
    }

    public function resolveRecord(): ?StickerDetail
    {

        $warnMsg = [];

        $sticker = $this->data['sticker_structure_detail_id'] ?? null;

        $stickerCode = StickerStructureDetail::where('sticker_id', $sticker)->first();
        if (!$stickerCode) {
            $warnMsg[] = "Sticker Id not found in Sticker Structure Detail";
        }

        $stickerId = $stickerCode->id;

        $user = User::where('name', $this->data['created_by'])->first();
        if (!$user) {
            $warnMsg[] = "User not found";
        }

        $designType = strtolower($this->data['design_element_type'] ?? '');

        $rules = [
            'text' => [
                'required' => ['string_x_value', 'string_y_value'],
                'allowed'  => [
                    'string_value',
                    'string_font',
                    'string_size',
                    'string_align',
                    'string_colour',
                    'string_x_value',
                    'string_y_value',
                ],
            ],

            'image' => [
                'required' => ['image_x', 'image_y', 'image_width', 'image_height'],
                'allowed'  => [
                    'image_x',
                    'image_y',
                    'image_width',
                    'image_height',
                ],
            ],

            'shape' => [
                'required' => ['shape_name', 'shape_pen_size', 'shape_x1_value', 'shape_y1_value', 'shape_x2_value', 'shape_y2_value'],
                'allowed'  => [
                    'shape_name',
                    'shape_pen_size',
                    'curve_radius',
                    'shape_x1_value',
                    'shape_y1_value',
                    'shape_x2_value',
                    'shape_y2_value',
                ],
            ],

            'qr' => [
                'required' => ['qr_value', 'qr_x_value', 'qr_y_value', 'qr_size'],
                'allowed'  => [
                    'qr_value',
                    'qr_align',
                    'qr_size',
                    'qr_x_value',
                    'qr_y_value',
                ],
            ],
        ];

         if (!isset($rules[$designType])) {
            $warnMsg[] = "Invalid Design Element Type: {$designType}";
        }

        if (isset($rules[$designType])) {
            foreach ($rules[$designType]['required'] as $field) {
                if (empty($this->data[$field])) {
                    $warnMsg[] = ucfirst($designType) . " requires {$field}";
                }
            }
        }

        $allElementFields = [
            'string_value','string_font','string_size','string_align','string_colour',
            'string_x_value','string_y_value',
            'image_x','image_y','image_width','image_height',
            'shape_name','shape_pen_size','curve_radius',
            'shape_x1_value','shape_y1_value','shape_x2_value','shape_y2_value',
            'qr_value','qr_align','qr_size','qr_x_value','qr_y_value',
        ];

        if (isset($rules[$designType])) {
            $allowed = $rules[$designType]['allowed'];

            foreach ($allElementFields as $field) {
                if (!in_array($field, $allowed, true) && !empty($this->data[$field])) {
                    $warnMsg[] = "Field {$field} is not allowed for {$designType} element";
                }
            }
        }

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

        StickerDetail::Create([
            'sticker_structure_detail_id' => $stickerId,
            'design_element_type' => $this->data['design_element_type'],
            'element_id' => $this->data['element_id'],
            'element_type' => $this->data['element_type'],
            'characteristics_type' => $this->data['characteristics_type'],
            'string_value' => $this->data['string_value'],
            'string_font' => $this->data['string_font'],
            'string_size' => $this->data['string_size'],
            'element_colour' => $this->data['element_colour'],
            'string_align' => $this->data['string_align'],
            'string_x_value' => $this->data['string_x_value'],
            'string_y_value' => $this->data['string_y_value'],
            'shape_name' => $this->data['shape_name'],
            'shape_pen_size' => $this->data['shape_pen_size'],
            'curve_radius' => $this->data['curve_radius'],
            'shape_x1_value' => $this->data['shape_x1_value'],
            'shape_y1_value' => $this->data['shape_y1_value'],
            'shape_x2_value' => $this->data['shape_x2_value'],
            'shape_y2_value' => $this->data['shape_y2_value'],
            'image_x' => $this->data['image_x'],
            'image_y' => $this->data['image_y'],
            'image_width' => $this->data['image_width'],
            'image_height' => $this->data['image_height'],
            'qr_value' => $this->data['qr_value'],
            'qr_align' => $this->data['qr_align'],
            'qr_size' => $this->data['qr_size'],
            'qr_x_value' => $this->data['qr_x_value'],
            'qr_y_value' => $this->data['qr_y_value'],
            'created_by' => $this->data['created_by'],
        ]);

        return null;

        //return new StickerDetail();
    }

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