<?php

namespace App\Filament\Imports;

use App\Models\Item;
use App\Models\ItemCharacteristic;
use App\Models\Plant;
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 StickerStructureDetailImporter extends Importer
{
    protected static ?string $model = StickerStructureDetail::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('item_characteristic_id')
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example('123456')
                ->label('ITEM CODE')
                ->rules(['required']),
            ImportColumn::make('sticker_id')
                ->requiredMapping()
                ->exampleHeader('Sticker ID')
                ->example('123456')
                ->label('STICKER ID')
                ->rules(['required']),
            ImportColumn::make('sticker_width')
                ->requiredMapping()
                ->exampleHeader('Sticker Width')
                ->example('90')
                ->label('STICKER WIDTH')
                ->rules(['required']),
            ImportColumn::make('sticker_height')
                ->requiredMapping()
                ->exampleHeader('Sticker Height')
                ->example('90')
                ->label('STICKER HEIGHT')
                ->rules(['required']),
            ImportColumn::make('sticker_lmargin')
                ->requiredMapping()
                ->exampleHeader('Sticker Left Margin')
                ->example('0')
                ->label('STICKER LEFT MARGIN')
                ->rules(['required']),
            ImportColumn::make('sticker_rmargin')
                ->requiredMapping()
                ->exampleHeader('Sticker Right Margin')
                ->example('0')
                ->label('STICKER RIGHT MARGIN')
                ->rules(['required']),
            ImportColumn::make('sticker_tmargin')
                ->requiredMapping()
                ->exampleHeader('Sticker Top Margin')
                ->example('0')
                ->label('STICKER TOP MARGIN')
                ->rules(['required']),
            ImportColumn::make('sticker_bmargin')
                ->requiredMapping()
                ->exampleHeader('Sticker Bottom Margin')
                ->example('0')
                ->label('STICKER BOTTOM MARGIN')
                ->rules(['required']),
            ImportColumn::make('created_by')
                ->requiredMapping()
                ->exampleHeader('Created By')
                ->example('RAW001234')
                ->label('CREATED BY')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?StickerStructureDetail
    {
        $warnMsg = [];

        $plant = Plant::where('code', $this->data['plant'])->first();

        if (!$plant) {
            $warnMsg[] = "Plant code not found";
        }

        // $item = null;
        // if ($plant) {
        //     $item = Item::where('code', $this->data['itemCharacteristic.item'])->where('plant_id', $plant->id)->first();
        // }
        // if (!$item) {
        //     $warnMsg[] = "Item not found";
        // }

        $itemCode = $this->data['item_characteristic_id'] ?? null;

        $item = Item::where('code', $itemCode)->first();
        if (!$item) {
            $warnMsg[] = "Item not found";
        }

        $itemChar = ItemCharacteristic::where('item_id', $item->id)->first();
        if (!$itemChar) {
            $warnMsg[] = "Item not found in item characteristic";
        }

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

        if (!empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }
        else { //if (empty($warnMsg))
            $stickerId = StickerStructureDetail::where('sticker_id', $this->data['sticker_id'])
            ->first();

            if ($stickerId) {
                throw new RowImportFailedException("Sticker ID already exist!");
            }
        }

        StickerStructureDetail::Create([
            'plant_id' => $plant->id,
            'item_characteristic_id' => $itemChar->id,
            'sticker_id' => $this->data['sticker_id'],
            'sticker_width' => $this->data['sticker_width'],
            'sticker_height' => $this->data['sticker_height'],
            'sticker_lmargin' => $this->data['sticker_lmargin'],
            'sticker_rmargin' => $this->data['sticker_rmargin'],
            'sticker_tmargin' => $this->data['sticker_tmargin'],
            'sticker_bmargin' => $this->data['sticker_bmargin'],
            'created_by' => $this->data['created_by'],
        ]);

        return null;

        //return new StickerStructureDetail();
    }

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