<?php

namespace App\Filament\Imports;

use App\Models\Block;
use App\Models\Plant;
use App\Models\Shift;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Str;

class ShiftImporter extends Importer
{
    protected static ?string $model = Shift::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('name')
                ->requiredMapping()
                ->exampleHeader('Shift Name')
                ->example('Day')
                ->label('Shift Name')
                ->rules(['required']),
            ImportColumn::make('start_time')
                ->requiredMapping()
                ->exampleHeader('Start Time')
                ->example('08:00:00')
                ->label('Start Time')
                ->rules(['required']),
            ImportColumn::make('duration')
                ->requiredMapping()
                ->numeric()
                ->exampleHeader('Shift Duration')
                ->example('11.30')
                ->label('Shift Duration')
                ->rules(['required']),
            ImportColumn::make('end_time')
                ->requiredMapping()
                ->exampleHeader('End Time')
                ->example('19:30:00')
                ->label('End Time')
                ->rules(['required']),
            ImportColumn::make('block')
                ->requiredMapping()
                ->exampleHeader('Block Name')
                ->example('Block A')
                ->label('Block Name')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('Plant Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('status')
                ->requiredMapping()
                ->exampleHeader('Active Status')
                ->example('Active')
                ->label('Active Status')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?Shift
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $plant = null;
        $block = null;
        if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
            $warnMsg[] = 'Invalid plant code found';
        } else {
            $plant = Plant::where('code', $plantCod)->first();
        }

        if (! $plant) {
            $warnMsg[] = 'Plant not found';
        } else {
            $block = Block::where('name', $this->data['block'])->where('plant_id', $plant->id)->first();
        }

        if (! $block) {
            $warnMsg[] = 'Block not found';
        }
        if (Str::length($this->data['duration']) < 0 || ! is_numeric($this->data['duration'])) {
            $warnMsg[] = 'Invalid duration found';
        }
        if (Str::length($this->data['start_time']) < 0) {
            $warnMsg[] = 'Invalid start time found';
        }
        if (Str::length($this->data['end_time']) < 0) {
            $warnMsg[] = 'Invalid end time found';
        }
        if (Str::length($this->data['status']) < 0 || $this->data['status'] != 'Active') {
            $warnMsg[] = 'Invalid shift status found';
        }

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

        $shift = Shift::where('name', $this->data['name'])
            ->where('plant_id', $plant->id)
            ->where('block_id', $block->id)
            ->first();

        if ($shift) {
            // Update only if necessary to avoid duplicate key error
            $shift->update([
                'start_time' => $this->data['start_time'],
                'duration' => $this->data['duration'],
                'end_time' => $this->data['end_time'],
                'status' => $this->data['status'],
            ]);

            return $shift;
        } else {
            // Safe to create new
            return Shift::create([
                'name' => $this->data['name'],
                'plant_id' => $plant->id,
                'block_id' => $block->id,
                'start_time' => $this->data['start_time'],
                'duration' => $this->data['duration'],
                'end_time' => $this->data['end_time'],
                'status' => $this->data['status'],
            ]);
        }
        // return Shift::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        // return new Shift();
    }

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