<?php

namespace App\Filament\Imports;

use App\Models\DealerVisitPlan;
use App\Models\EmployeeMaster;
use App\Models\Plant;
use Carbon\Carbon;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Str;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Illuminate\Support\Facades\Log;

class DealerVisitPlanImporter extends Importer
{
    protected static ?string $model = DealerVisitPlan::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('name')
                ->requiredMapping()
                ->exampleHeader('Dealer Name')
                ->example('Suresh')
                ->label('Dealer Name')
                ->rules(['required']),
            ImportColumn::make('company')
                ->requiredMapping()
                ->exampleHeader('Dealer Company')
                ->example('Suresh Traders')
                ->label('Dealer Company')
                ->rules(['required']),
            ImportColumn::make('visit_plan_date')
                ->requiredMapping()
                ->exampleHeader('Visit Plan Date')
                ->example('2026-07-20')
                ->label('Visit Plan Date'),
            ImportColumn::make('organizer')
                ->requiredMapping()
                ->exampleHeader('Organizer')
                ->example('Ramesh')
                ->label('Organizer'),
            ImportColumn::make('employee_master_id')
                ->requiredMapping()
                ->exampleHeader('Receipient Employee Code')
                ->example('RAS001234')
                ->label('Receipient Employee Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('number_of_person')
                ->requiredMapping()
                ->exampleHeader('Number Of Person')
                ->example('10')
                ->label('Number Of Person'),
            ImportColumn::make('purpose_of_visit')
                ->requiredMapping()
                ->exampleHeader('Purpose Of Visit')
                ->example('Meeting')
                ->label('Purpose Of Visit'),
            ImportColumn::make('status')
                ->requiredMapping()
                ->exampleHeader('Status')
                ->example('Planned/Completed')
                ->label('Status'),
        ];
    }

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

        $user = null;
        $dealerName = trim($this->data['name']);
        $dealerCompany = trim($this->data['company']);
        $visitPlanDt = trim($this->data['visit_plan_date']);
        $organizer = trim($this->data['organizer']);
        $employeeCode = trim($this->data['employee_master_id']);
        $noOfPerson = trim($this->data['number_of_person']);
        $purposeOfVisit = trim($this->data['purpose_of_visit']);
        $status = trim($this->data['status']);
        $user = Filament::auth()->user()->name;

        if (Str::length($employeeCode) < 5) {
            $warnMsg[] = 'Invalid receipient employee number found!';
        }
        if (! empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        $employeeId = EmployeeMaster::where('code', $employeeCode)->first();

        $eId = $employeeId->id;

        DealerVisitPlan::updateOrCreate(
            [
                'name' => $dealerName,
                'company' => $dealerCompany,
                'visit_plan_date' => Carbon::createFromFormat('d-m-Y', $visitPlanDt)->format('Y-m-d'),
                'organizer' => $organizer,
                'employee_master_id' => $eId,
                'number_of_person' => $noOfPerson,
                'purpose_of_visit' => $purposeOfVisit,
                'status' => $status,
                'created_by' => $user,
                'updated_by' => $user,
            ]
        );

        return null;

        // return new DealerVisitPlan();
    }

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