<?php

namespace App\Filament\Imports;

use App\Models\Test;
use App\Models\TestCategory;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;

class TestImporter extends Importer
{
    protected static ?string $model = Test::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('name')
                ->label('Name (Arabic)')
                ->requiredMapping()
                ->rules(['required', 'string'])
                ->guess(['name', 'name_ar', 'arabic', 'test name', 'اسم التحليل', 'الاسم']),
            
            ImportColumn::make('name_en')
                ->label('Name (English)')
                ->fillRecordUsing(function (mixed $state, \Illuminate\Database\Eloquent\Model $record): void {
                    if (blank($state)) {
                        return;
                    }
                    $record->setTranslation('name', 'en', (string) $state);
                })
                ->guess(['name_en', 'name en', 'english', 'english name', 'الاسم بالإنجليزي']),
            
            ImportColumn::make('code')
                ->label('Test Code')
                ->guess(['code', 'test code', 'كود', 'رمز التحليل']),
            
            ImportColumn::make('category')
                ->label('Category')
                ->fillRecordUsing(function (mixed $state, \Illuminate\Database\Eloquent\Model $record): void {
                    if (blank($state)) {
                        return;
                    }
                    $cat = TestCategory::all()->first(function (TestCategory $c) use ($state) {
                        $name = $c->name;
                        if (is_array($name)) {
                            return ($name['ar'] ?? '') === $state || ($name['en'] ?? '') === $state;
                        }
                        return (string) $name === (string) $state;
                    });
                    if ($cat) {
                        $record->test_category_id = $cat->id;
                    }
                })
                ->guess(['category', 'category name', 'فئة', 'التصنيف', 'test category']),

            ImportColumn::make('price')
                ->label('Price')
                ->numeric()
                ->rules(['integer', 'min:0'])
                ->guess(['price', 'السعر', 'cost', 'amount']),

            ImportColumn::make('is_active')
                ->boolean()
                ->label('Active')
                ->rules(['boolean'])
                ->guess(['is_active', 'active', 'نشط', 'status']),
        ];
    }

    public function resolveRecord(): ?Test
    {
        $test = Test::firstOrNew([
            'code' => $this->data['code'] ?? null,
            'name' => $this->data['name'],
        ]);

        if (isset($this->data['name_en']) && !empty($this->data['name_en'])) {
            $test->setTranslation('name', 'en', $this->data['name_en']);
        }

        // Default active = true when not provided; category stays null when not mapped or blank
        if (! array_key_exists('is_active', $this->data) || $this->data['is_active'] === '' || $this->data['is_active'] === null) {
            $test->is_active = true;
        }
        if (! array_key_exists('category', $this->data) || $this->data['category'] === '' || $this->data['category'] === null) {
            $test->test_category_id = null;
        }

        return $test;
    }

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