<?php

namespace App\Filament\Imports;

use App\Models\Line;
use App\Models\Plant;
use App\Models\RejectReason;
use App\Models\User;
use App\Models\WorkGroupMaster;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Str;

class RejectReasonImporter extends Importer
{
    protected static ?string $model = RejectReason::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Name')
                ->example('Ransar Industries-I')
                ->label('Plant Name')
                ->relationship(resolveUsing:'name')
                ->rules(['required']),
            ImportColumn::make('line')
                ->requiredMapping()
                ->exampleHeader('Line Name')
                ->example('4 inch pump line')
                ->label('Line Name')
                ->relationship(resolveUsing:'name')
                ->rules(['required']),
            ImportColumn::make('workGroupMaster')
                ->requiredMapping()
                ->exampleHeader('Work Group Name')
                ->example('RMGCEABC')
                ->label('Work Group Name')
                ->relationship(resolveUsing:'name')
                ->rules(['required']),
            ImportColumn::make('code')
                ->requiredMapping()
                ->exampleHeader('Code')
                ->example('RR01')
                ->label('Code')
                ->rules(['required']),
            ImportColumn::make('reason')
                ->requiredMapping()
                ->exampleHeader('Reason')
                ->example('Pump voltage issue')
                ->label('Reason')
                ->rules(['required']),
            ImportColumn::make('created_by')
                ->requiredMapping()
                ->exampleHeader('Created By')
                ->example('Admin')
                ->label('Created By')
                ->rules(['required']),
        ];
    }

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

        //Validate Plant
        $plant = Plant::where('name', $this->data['plant'])->first();
        if (!$plant) {
            $warnMsg[] = "Plant '{$this->data['plant']}' not found";
        }

        // //Validate Line
        // $line = Line::where('name', $this->data['line'] ?? null)->first();
        // if (!$line) {
        //     $warnMsg[] = "Line '{$this->data['line']}' not found";
        // }
        $line = null;
        if ($plant) {
            $line = Line::where('name', $this->data['line'] ?? null)
                ->where('plant_id', $plant->id)
                ->first();
        }

        if (!$line) {
            $warnMsg[] = "Line '{$this->data['line']}' not found in Plant '{$this->data['plant']}'";
        }


        //Validate WorkGroupMaster
        $workGroup = WorkGroupMaster::where('name', $this->data['workGroupMaster'] ?? null)->first();
        if (!$workGroup) {
            $warnMsg[] = "Work Group '{$this->data['workGroupMaster']}' not found";
        }

        //Validate Reason
        $reason = trim($this->data['reason']);
        if (Str::length($reason) <= 0) {
            $warnMsg[] = "Invalid reason found";
        }

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

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

        $existingRecord = RejectReason::where('plant_id', $plant->id)
            ->where('line_id', $line->id)
            ->where('work_group_master_id', $workGroup->id)
            ->where('code', $this->data['code'])
            ->first();

        if ($existingRecord) {
            throw new RowImportFailedException(
                "Duplicate found! Combination of Plant '{$plant->name}', Line '{$line->name}', Work Group '{$workGroup->name}', and Code '{$this->data['code']}' must be unique."
            );
        }

        //Insert or Update
        RejectReason::updateOrCreate(
            [
                'plant_id' => $plant->id,
                'line_id' => $line->id,
                'work_group_master_id' => $workGroup->id,
                'code' => $this->data['code'],
            ],
            [
                'reason' => $reason,
                'created_by' => $user->name,
            ]
        );

        return null;
    }

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