<?php

namespace Database\Seeders;

use App\Models\Harvest;
use App\Models\PlannedTask;
use App\Models\VineyardRow;
use App\Models\Spraying;
use App\Models\Fertilization;
use App\Models\Watering;
use App\Models\Pruning;
use App\Models\Treatment;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PlannedTaskSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get all vineyard rows
        $vineyardRows = VineyardRow::with('varietyVariation.grapeVariety')->get();

        if ($vineyardRows->isEmpty()) {
            if ($this->command) {
                $this->command->warn('No vineyard rows found. Skipping PlannedTaskSeeder.');
            }
            return;
        }

        // ==========================================
        // PLANNED TREATMENTS (Not yet executed)
        // ==========================================

        // Spraying - planned for this week and next week
        $sprayingTasks = [
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(2),
                'note' => 'Fungicide application for mildew prevention',
                'rows' => [1, 2, 4, 5, 13], // Grüner Veltliner, Riesling, Müller Thurgau rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(5),
                'note' => 'Copper sulfate treatment',
                'rows' => [7, 8, 11], // Blaufränkisch and St. Laurent rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(9),
                'note' => 'Organic pest control spray',
                'rows' => [16, 17], // Chardonnay rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(11),
                'note' => 'Sulfur spray for powdery mildew',
                'rows' => [3, 6, 14, 15], // Selected white variety rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(13),
                'note' => 'Insect protection spray',
                'rows' => [9, 10, 12], // Red variety rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(16),
                'note' => 'Botrytis prevention treatment',
                'rows' => [1, 4, 7, 8], // Mixed varieties
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->addDays(20),
                'note' => 'Final pre-harvest fungicide',
                'rows' => [13, 14, 16], // Selected rows for early harvest
            ],
        ];

        // Fertilization - planned for upcoming weeks
        $fertilizationTasks = [
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(1),
                'note' => 'Spring nitrogen fertilization',
                'rows' => [1, 3, 4, 6], // Selected Grüner Veltliner and Riesling rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(7),
                'note' => 'Potassium supplement application',
                'rows' => [7, 9, 10, 11, 12, 16, 18], // Blaufränkisch, St. Laurent, and Chardonnay rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(12),
                'note' => 'Organic compost distribution',
                'rows' => [13, 14, 15], // All Müller Thurgau rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(14),
                'note' => 'Magnesium foliar spray',
                'rows' => [2, 5, 17], // Selected white variety rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(18),
                'note' => 'Calcium nitrate application',
                'rows' => [7, 8, 9, 11], // Red variety rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(21),
                'note' => 'Phosphorus enrichment',
                'rows' => [1, 2, 3, 4, 5, 6], // Grüner Veltliner and Riesling rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(25),
                'note' => 'Pre-harvest nutrient boost',
                'rows' => [13, 14, 16, 18], // Early harvest rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->addDays(28),
                'note' => 'Micronutrient foliar feed',
                'rows' => [10, 12, 15], // Selected rows
            ],
        ];

        // Watering - planned for this week
        $wateringTasks = [
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(3),
                'note' => 'Deep irrigation cycle',
                'rows' => [1, 2, 3, 4, 5, 13, 14, 16], // Multiple white variety rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(6),
                'note' => 'Evening drip irrigation',
                'rows' => [7, 8, 9, 11], // Red variety rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(8),
                'note' => 'Morning light watering',
                'rows' => [15, 17, 18], // Chardonnay and Müller Thurgau rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(10),
                'note' => 'Stress relief deep watering',
                'rows' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // Most rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(13),
                'note' => 'Targeted root zone irrigation',
                'rows' => [13, 14, 15], // All Müller Thurgau rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(15),
                'note' => 'Drip system maintenance watering',
                'rows' => [16, 17, 18], // All Chardonnay rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(17),
                'note' => 'Pre-harvest moisture regulation',
                'rows' => [1, 4, 5, 13, 14], // Early harvest rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(22),
                'note' => 'Post-treatment irrigation',
                'rows' => [7, 8, 9, 10, 11, 12], // Red variety rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->addDays(24),
                'note' => 'Controlled stress watering',
                'rows' => [2, 3, 6], // Selected white rows
            ],
        ];

        // Pruning - planned for upcoming days
        $pruningTasks = [
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(4),
                'note' => 'Summer green pruning - remove excess shoots',
                'rows' => [1, 2, 4, 5], // Specific Grüner Veltliner and Riesling rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(8),
                'note' => 'Canopy management - leaf thinning',
                'rows' => [7, 8, 9, 11, 12], // Blaufränkisch and St. Laurent rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(11),
                'note' => 'Lateral shoot removal',
                'rows' => [13, 14, 15], // Müller Thurgau rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(14),
                'note' => 'Cluster thinning for quality',
                'rows' => [3, 6, 16, 17], // Selected rows for premium wine
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(19),
                'note' => 'Leaf removal around clusters',
                'rows' => [1, 2, 3, 4, 5, 6], // White variety rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(23),
                'note' => 'Secondary shoot trimming',
                'rows' => [10, 11, 12], // Red variety rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->addDays(26),
                'note' => 'Pre-harvest canopy opening',
                'rows' => [13, 14, 16, 18], // Early harvest rows
            ],
        ];

        // Create planned tasks (not executed)
        $modelMap = [
            'Spraying' => [Spraying::class, ['pesticide' => 'Standard pesticide', 'concentration' => 2.5]],
            'Fertilization' => [Fertilization::class, ['substance' => 'NPK fertilizer', 'concentration' => 5.0]],
            'Watering' => [Watering::class, ['time_interval' => 60, 'amount' => 100.0]],
            'Pruning' => [Pruning::class, ['method' => 'Manual pruning', 'percentage_removed' => 30]],
        ];

        foreach ([$sprayingTasks, $fertilizationTasks, $wateringTasks, $pruningTasks] as $taskGroup) {
            foreach ($taskGroup as $taskData) {
                foreach ($taskData['rows'] as $rowId) {
                    $row = $vineyardRows->firstWhere('id', $rowId);

                    if ($row) {
                        // Create the base treatment
                        $treatment = Treatment::create([
                            'row_id' => $row->id,
                            'note' => $taskData['note'],
                        ]);

                        // Create the specific treatment type
                        [$modelClass, $specificData] = $modelMap[$taskData['type']];
                        $specificTreatment = $modelClass::create(array_merge(
                            ['treatment_id' => $treatment->treatment_id],
                            $specificData,
                            ['note' => $taskData['note']]
                        ));

                        // Create planned task linked to the specific treatment
                        PlannedTask::create([
                            'type' => $taskData['type'],
                            'planned_date' => $taskData['planned_date'],
                            'execution_date' => null, // Not yet executed
                            'note' => $taskData['note'],
                            'taskable_id' => $treatment->treatment_id,
                            'taskable_type' => $modelClass,
                        ]);
                    }
                }
            }
        }

        // ==========================================
        // COMPLETED TREATMENTS (Recently executed)
        // ==========================================

        $completedTreatments = [
            [
                'type' => 'Spraying',
                'planned_date' => now()->subDays(10),
                'execution_date' => now()->subDays(10),
                'note' => 'Early season sulfur spray',
                'rows' => [1, 2, 3, 4, 6, 13, 15], // Multiple white variety rows
            ],
            [
                'type' => 'Fertilization',
                'planned_date' => now()->subDays(7),
                'execution_date' => now()->subDays(7),
                'note' => 'Base fertilization with compost',
                'rows' => [7, 8, 11, 12], // Red variety rows
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->subDays(5),
                'execution_date' => now()->subDays(5),
                'note' => 'Post-planting irrigation',
                'rows' => [16, 17, 18], // All Chardonnay rows
            ],
            [
                'type' => 'Pruning',
                'planned_date' => now()->subDays(3),
                'execution_date' => now()->subDays(3),
                'note' => 'Winter pruning final pass',
                'rows' => [1, 3, 4, 6], // Selected Grüner Veltliner and Riesling rows
            ],
            [
                'type' => 'Spraying',
                'planned_date' => now()->subDays(14),
                'execution_date' => now()->subDays(15),
                'note' => 'Preventive copper treatment',
                'rows' => [7, 9, 10, 11, 16, 17], // Mix of red varieties and Chardonnay
            ],
            [
                'type' => 'Watering',
                'planned_date' => now()->subDays(12),
                'execution_date' => now()->subDays(12),
                'note' => 'Emergency drought watering',
                'rows' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15], // Most rows
            ],
        ];

        foreach ($completedTreatments as $taskData) {
            foreach ($taskData['rows'] as $rowId) {
                $row = $vineyardRows->firstWhere('id', $rowId);

                if ($row) {
                    // Create the base treatment
                    $treatment = Treatment::create([
                        'row_id' => $row->id,
                        'note' => $taskData['note'],
                    ]);

                    // Create the specific treatment type
                    [$modelClass, $specificData] = $modelMap[$taskData['type']];
                    $specificTreatment = $modelClass::create(array_merge(
                        ['treatment_id' => $treatment->treatment_id],
                        $specificData,
                        ['note' => $taskData['note']]
                    ));

                    // Create planned task linked to the specific treatment (already executed)
                    PlannedTask::create([
                        'type' => $taskData['type'],
                        'planned_date' => $taskData['planned_date'],
                        'execution_date' => $taskData['execution_date'],
                        'note' => $taskData['note'],
                        'taskable_id' => $treatment->treatment_id,
                        'taskable_type' => $modelClass,
                    ]);
                }
            }
        }

        // ==========================================
        // PLANNED HARVESTS (Near-term - within 2 weeks)
        // ==========================================

        $nearTermHarvests = [
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(3),
                'note' => 'Test harvest - sugar content assessment',
                'rows' => [1], // Single Grüner Veltliner row
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(6),
                'note' => 'Early white grape harvest',
                'rows' => [13, 14, 4, 5], // Müller Thurgau and Riesling rows
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(10),
                'note' => 'Chardonnay harvest for reserve wine',
                'rows' => [16, 18], // Selected Chardonnay rows
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(12),
                'note' => 'Riesling harvest for late vintage',
                'rows' => [2, 3], // Selected Riesling rows
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(15),
                'note' => 'Grüner Veltliner main harvest',
                'rows' => [1, 2, 3], // Grüner Veltliner rows
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(18),
                'note' => 'Müller Thurgau harvest',
                'rows' => [15], // Single Müller Thurgau row
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addDays(21),
                'note' => 'Chardonnay harvest continuation',
                'rows' => [17], // Remaining Chardonnay row
            ],
        ];

        foreach ($nearTermHarvests as $taskData) {
            foreach ($taskData['rows'] as $rowId) {
                $row = $vineyardRows->firstWhere('id', $rowId);

                if ($row) {
                    // Create harvest model
                    $harvest = Harvest::create([
                        'vineyard_row_id' => $row->id,
                        'variety_variation_id' => $row->variety_variation_id,
                        'date' => $taskData['planned_date'],
                        'sugar_content' => 0,
                        'weight' => 0,
                        'quality' => null,
                        'user_id' => null,
                        'notes' => $taskData['note'],
                    ]);

                    // Create planned task linked to the harvest
                    PlannedTask::create([
                        'type' => $taskData['type'],
                        'planned_date' => $taskData['planned_date'],
                        'execution_date' => null,
                        'note' => $taskData['note'],
                        'taskable_id' => $harvest->id,
                        'taskable_type' => Harvest::class,
                    ]);
                }
            }
        }

        // ==========================================
        // PLANNED HARVESTS (Future - beyond 2 weeks)
        // ==========================================

        $futureHarvests = [
            [
                'type' => 'Harvest',
                'planned_date' => now()->addMonths(2),
                'note' => 'Early harvest for sparkling wine production',
                'rows' => [17], // Single Chardonnay row
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addMonths(3),
                'note' => 'Main white grape harvest',
                'rows' => [1, 2, 3, 4, 5, 6, 13, 14, 15], // All white variety rows
            ],
            [
                'type' => 'Harvest',
                'planned_date' => now()->addMonths(3)->addDays(7),
                'note' => 'Red grape harvest',
                'rows' => [7, 8, 9, 10, 11, 12], // All red variety rows
            ],
        ];

        foreach ($futureHarvests as $taskData) {
            foreach ($taskData['rows'] as $rowId) {
                $row = $vineyardRows->firstWhere('id', $rowId);

                if ($row) {
                    // Create harvest model
                    $harvest = Harvest::create([
                        'vineyard_row_id' => $row->id,
                        'variety_variation_id' => $row->variety_variation_id,
                        'date' => $taskData['planned_date'],
                        'sugar_content' => 0,
                        'weight' => 0,
                        'quality' => null,
                        'user_id' => null,
                        'notes' => $taskData['note'],
                    ]);

                    // Create planned task linked to the harvest
                    PlannedTask::create([
                        'type' => $taskData['type'],
                        'planned_date' => $taskData['planned_date'],
                        'execution_date' => null,
                        'note' => $taskData['note'],
                        'taskable_id' => $harvest->id,
                        'taskable_type' => Harvest::class,
                    ]);
                }
            }
        }

        // Count and report
        $totalPlanned = PlannedTask::whereNull('execution_date')->count();
        $totalCompleted = PlannedTask::whereNotNull('execution_date')->count();

        if ($this->command) {
            $this->command->info("✓ Created {$totalPlanned} planned tasks and {$totalCompleted} completed tasks");
        }
    }
}
