<?php

namespace App\Filament\Imports;

use App\Models\Block;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionPlan;
use App\Models\Shift;
use App\Models\User;
use Carbon\Carbon;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Str;

class ProductionPlanImporter extends Importer
{
    protected static ?string $model = ProductionPlan::class;

    public static function getColumns(): array
    {
        return [
            // ImportColumn::make('created_at')
            //     ->requiredMapping()
            //     ->exampleHeader('Created DateTime')
            //     ->example(['01-01-2025 08:00:00', '01-01-2025 19:30:00'])
            //     ->label('Created DateTime')
            //     ->rules(['required']),

            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example(['1000', '1000'])
                ->label('Plant Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('line')
                ->requiredMapping()
                ->exampleHeader('Line Name')
                ->example(['4 inch pump line', '4 inch pump line'])
                ->label('Line Name')
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),
            ImportColumn::make('item')
                ->requiredMapping()
                ->exampleHeader('Item Code')
                ->example(['123456', '210987'])
                ->label('Item Code')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('plan_quantity')
                ->requiredMapping()
                ->exampleHeader('Plan Quantity')
                ->example(['500', '450'])
                ->label('Plan Quantity')
                ->numeric()
                ->rules(['required', 'integer']),
            // ImportColumn::make('production_quantity')
            //     ->requiredMapping()
            //     ->exampleHeader('Production Quantity')
            //     ->example(['0', '0'])
            //     ->label('Production Quantity')
            //     ->numeric()
            //     ->rules(['required', 'integer']),

            // ImportColumn::make('block_reference')
            //     ->requiredMapping() // Or optionalMapping() if not always present
            //     ->exampleHeader('Block Name')
            //     ->example(['Block A', 'Block A'])
            //     ->label('Block Name')
            //     ->rules(['required']), // Or remove if not required
            // ImportColumn::make('shift')
            //     ->requiredMapping()
            //     ->exampleHeader('Shift Name') // ID
            //     ->example(['Day', 'Night']) // '2', '7'
            //     ->label('Shift Name') // ID
            //     ->relationship(resolveUsing: 'name')
            //     ->rules(['required']),

            // ImportColumn::make('updated_at')
            //     ->requiredMapping()
            //     ->exampleHeader('Updated DateTime')
            //     ->example(['01-01-2025 08:00:00', '01-01-2025 19:30:00'])
            //     ->label('Updated DateTime')
            //     ->rules(['required']),
            // ImportColumn::make('operator_id')
            //     ->requiredMapping()
            //     ->exampleHeader('Operator ID')
            //     ->example([Filament::auth()->user()->name, Filament::auth()->user()->name])
            //     ->label('Operator ID')
            //     ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?ProductionPlan
    {
        $warnMsg = [];
        $plantCod = $this->data['plant'];
        $itemCod = $this->data['item'];
        $plant = null;
        $line = 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 {
            $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
        }

        if (! $line) {
            $warnMsg[] = 'Line not found';
        }

        if (Str::length($itemCod) < 6 || ! is_numeric($itemCod)) {
            $warnMsg[] = 'Invalid item code found';
        } else {
            $item = Item::where('code', $itemCod)->first();
        }

        if (! $item) {
            $warnMsg[] = 'Item not found';
        }

        $plantId = $plant->id;

        $itemAgaPlant = Item::where('plant_id', $plantId)->where('code', $itemCod)->first();

        if(!$itemAgaPlant){
            $warnMsg[] = 'Item not found against plant code';
        }

        $user = Filament::auth()->user();

        $operatorName = $user->name;

        if (Str::length($this->data['plan_quantity']) < 0 || ! is_numeric($this->data['plan_quantity']) || $this->data['plan_quantity'] <= 0) {
            $warnMsg[] = 'Invalid plan quantity found';
        }

        if (! empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        } else {
            $productionPlan = ProductionPlan::where('plant_id', $plant->id)
                ->where('line_id', $line->id)
                ->where('item_id', $itemAgaPlant->id)
                ->latest()
                ->first();

            if ($productionPlan) {

                $recordDate = now();
                $month = $recordDate->month;
                $year = $recordDate->year;

                $previousRecord = ProductionPlan::where('plant_id', $plant->id)
                    ->whereMonth('created_at', $month)
                    ->whereYear('created_at', $year)
                    ->first();

                $workingDays = $previousRecord?->working_days ?? null;

                $productionPlan->update([
                    'plan_quantity' => $this->data['plan_quantity'],
                    'working_days' => $workingDays,
                    'operator_id' => $operatorName,
                ]);
                $productionPlan->save();

                return null;
            }
        }

        $recordDate = now();
        $month = $recordDate->month;
        $year = $recordDate->year;

        $previousRecord = ProductionPlan::where('plant_id', $plant->id)
            ->whereMonth('created_at', $month)
            ->whereYear('created_at', $year)
            ->first();

        $workingDays = $previousRecord?->working_days ?? null;

        ProductionPlan::updateOrCreate([
            'plant_id' => $plant->id,
            'line_id' => $line->id,
            'item_id' => $itemAgaPlant->id,
            // 'shift_id' => $shift->id,
            'plan_quantity' => $this->data['plan_quantity'],
            'working_days' => $workingDays,
            'created_at' =>now(),
            'updated_at' => now(),
            'operator_id' => $operatorName,
        ]);

        return null;
    }

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