<?php

namespace Database\Seeders;

use App\Models\Category;
use App\Models\Product;
use App\Models\SubCategory;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class CatalogSeeder extends Seeder
{
    public function run(): void
    {
        // Define high-quality images for specific categories/subcategories
        $categoryImages = [
            'Fruits & Vegetables' => 'https://images.unsplash.com/photo-1610832958506-aa56368176cf?auto=format&fit=crop&w=600&q=80',
            'Dairy, Bread & Eggs' => 'https://images.unsplash.com/photo-1628088062854-d1870b4553da?auto=format&fit=crop&w=600&q=80',
            'Atta, Rice & Dal' => 'https://images.unsplash.com/photo-1586201375761-83865001e31c?auto=format&fit=crop&w=600&q=80',
            'Masala & Spices' => 'https://images.unsplash.com/photo-1596040033229-a9821ebd058d?auto=format&fit=crop&w=600&q=80',
            'Snacks & Munchies' => 'https://images.unsplash.com/photo-1621939514649-28b12e81658b?auto=format&fit=crop&w=600&q=80',
            'Beverages' => 'https://images.unsplash.com/photo-1600271886742-f049cd451bba?auto=format&fit=crop&w=600&q=80',
            'Breakfast & Instant Food' => 'https://images.unsplash.com/photo-1598373182133-52452f7691f6?auto=format&fit=crop&w=600&q=80',
            'Personal Care' => 'https://images.unsplash.com/photo-1612817289591-f47d610000ef?auto=format&fit=crop&w=600&q=80',
            'Home Care' => 'https://images.unsplash.com/photo-1585421514738-01798e824255?auto=format&fit=crop&w=600&q=80',
            'Baby Care' => 'https://images.unsplash.com/photo-1519689680058-324335c77eba?auto=format&fit=crop&w=600&q=80',
            'Meat, Fish & Eggs' => 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?auto=format&fit=crop&w=600&q=80',
            'Frozen Food' => 'https://images.unsplash.com/photo-1565557623262-b51c2513a641?auto=format&fit=crop&w=600&q=80',
        ];

        $subCategoryImages = [
            'Fresh Fruits' => 'https://images.unsplash.com/photo-1610832958506-aa56368176cf?auto=format&fit=crop&w=600&q=80',
            'Fresh Vegetables' => 'https://images.unsplash.com/photo-1597362925123-77861d3fbac7?auto=format&fit=crop&w=600&q=80',
            'Milk & Curd' => 'https://images.unsplash.com/photo-1628088062854-d1870b4553da?auto=format&fit=crop&w=600&q=80',
            'Butter & Cheese' => 'https://images.unsplash.com/photo-1624447004468-4a1135b6f0e0?auto=format&fit=crop&w=600&q=80',
            'Bread & Buns' => 'https://images.unsplash.com/photo-1598373182133-52452f7691f6?auto=format&fit=crop&w=600&q=80',
            'Eggs' => 'https://images.unsplash.com/photo-1598965402089-897ce52e8355?auto=format&fit=crop&w=600&q=80',
            'Atta & Flours' => 'https://images.unsplash.com/photo-1626074353765-517a681e40be?auto=format&fit=crop&w=600&q=80',
            'Rice & Rice Products' => 'https://images.unsplash.com/photo-1586201375761-83865001e31c?auto=format&fit=crop&w=600&q=80',
            'Whole Spices' => 'https://images.unsplash.com/photo-1596040033229-a9821ebd058d?auto=format&fit=crop&w=600&q=80',
            'Chips & Crisps' => 'https://images.unsplash.com/photo-1621939514649-28b12e81658b?auto=format&fit=crop&w=600&q=80',
            'Chocolates & Candies' => 'https://images.unsplash.com/photo-1606312619070-d48b4c652a52?auto=format&fit=crop&w=600&q=80',
            'Tea' => 'https://images.unsplash.com/photo-1571934811356-5cc55449d0a4?auto=format&fit=crop&w=600&q=80',
            'Coffee' => 'https://images.unsplash.com/photo-1559496417-e7f25cb247f3?auto=format&fit=crop&w=600&q=80',
            'Soft Drinks' => 'https://images.unsplash.com/photo-1622483767028-3f66f32aef97?auto=format&fit=crop&w=600&q=80',
            'Fruit Juices' => 'https://images.unsplash.com/photo-1600271886742-f049cd451bba?auto=format&fit=crop&w=600&q=80',
            'Noodles & Pasta' => 'https://images.unsplash.com/photo-1612929633738-8fe44f7ec841?auto=format&fit=crop&w=600&q=80',
            'Sauces & Spreads' => 'https://images.unsplash.com/photo-1607301405390-d831c242f59b?auto=format&fit=crop&w=600&q=80',
            'Diapers & Wipes' => 'https://images.unsplash.com/photo-1519689680058-324335c77eba?auto=format&fit=crop&w=600&q=80', // Baby specific
            'Baby Food' => 'https://images.unsplash.com/photo-1584278434560-de67b8d0b679?auto=format&fit=crop&w=600&q=80',
            'Chicken' => 'https://images.unsplash.com/photo-1604503468506-a8da13d82791?auto=format&fit=crop&w=600&q=80',
            'Fish & Seafood' => 'https://images.unsplash.com/photo-1534483852509-1fa3d349d86b?auto=format&fit=crop&w=600&q=80',
        ];

        // Define a professional hierarchy of Categories and SubCategories
        $catalog = [
            'Fruits & Vegetables' => [
                'Fresh Fruits' => ['Apple', 'Banana', 'Orange', 'Mango', 'Grapes', 'Papaya', 'Pineapple', 'Watermelon', 'Pomegranate', 'Kiwi', 'Strawberry', 'Guava', 'Pear', 'Muskmelon', 'Peach', 'Plum'],
                'Fresh Vegetables' => ['Potato', 'Onion', 'Tomato', 'Cauliflower', 'Cabbage', 'Spinach', 'Carrot', 'Cucumber', 'Bell Pepper', 'Brinjal', 'Lady Finger', 'Bottle Gourd', 'Bitter Gourd', 'Beans', 'Beetroot', 'Radish'],
                'Herbs & Seasonings' => ['Coriander', 'Mint Leaves', 'Ginger', 'Garlic', 'Green Chilli', 'Lemon', 'Curry Leaves', 'Parsley', 'Basil', 'Spring Onion'],
                'Exotic Fruits & Veggies' => ['Avocado', 'Broccoli', 'Zucchini', 'Dragon Fruit', 'Blueberries', 'Cherry Tomato', 'Red Cabbage', 'Celery', 'Asparagus', 'Lettuce'],
                'Organic Produce' => ['Organic Apple', 'Organic Tomato', 'Organic Spinach', 'Organic Carrot', 'Organic Potato', 'Organic Banana']
            ],
            'Dairy, Bread & Eggs' => [
                'Milk & Curd' => ['Fresh Milk', 'Toned Milk', 'Curd', 'Buttermilk', 'Flavoured Milk', 'Yogurt', 'Soy Milk', 'Almond Milk'],
                'Paneer, Tofu & Cream' => ['Malai Paneer', 'Fresh Paneer', 'Tofu', 'Fresh Cream', 'Cooking Butter', 'Low Fat Paneer'],
                'Butter & Cheese' => ['Salted Butter', 'Unsalted Butter', 'Cheese Slices', 'Cheese Cubes', 'Mozzarella Cheese', 'Cheese Spread', 'Feta Cheese', 'Cheddar Cheese'],
                'Bread & Buns' => ['White Bread', 'Brown Bread', 'Multigrain Bread', 'Sandwich Bread', 'Burger Buns', 'Pav', 'Pizza Base', 'Garlic Bread'],
                'Eggs' => ['Farm Eggs', 'Brown Eggs', 'Protein Eggs', 'Organic Eggs', 'Quail Eggs']
            ],
            'Atta, Rice & Dal' => [
                'Atta & Flours' => ['Whole Wheat Atta', 'Multigrain Atta', 'Maida', 'Besan', 'Rice Flour', 'Sooji', 'Ragi Flour', 'Corn Flour', 'Bajra Flour'],
                'Rice & Rice Products' => ['Basmati Rice', 'Sona Masoori Rice', 'Brown Rice', 'Poha', 'Idli Rice', 'Jasmine Rice', 'Red Rice', 'Puffed Rice'],
                'Dals & Pulses' => ['Toor Dal', 'Moong Dal', 'Masoor Dal', 'Chana Dal', 'Urad Dal', 'Rajma', 'Kabuli Chana', 'Green Gram', 'Horse Gram', 'Black Eyed Peas'],
                'Edible Oils & Ghee' => ['Sunflower Oil', 'Mustard Oil', 'Olive Oil', 'Cow Ghee', 'Buffalo Ghee', 'Groundnut Oil', 'Rice Bran Oil', 'Coconut Oil', 'Sesame Oil'],
                'Salt, Sugar & Jaggery' => ['Iodised Salt', 'Rock Salt', 'Sugar', 'Brown Sugar', 'Jaggery Cubes', 'Sugar Free', 'Honey', 'Palm Sugar']
            ],
            'Masala & Spices' => [
                'Whole Spices' => ['Cumin Seeds', 'Mustard Seeds', 'Black Pepper', 'Cardamom', 'Cloves', 'Cinnamon Stick', 'Bay Leaf', 'Star Anise', 'Fennel Seeds', 'Fenugreek Seeds'],
                'Powdered Spices' => ['Turmeric Powder', 'Chilli Powder', 'Coriander Powder', 'Cumin Powder', 'Garam Masala', 'Amchur Powder', 'Dry Ginger Powder', 'Black Salt'],
                'Cooking Pastes' => ['Ginger Garlic Paste', 'Tomato Puree', 'Tamarind Paste', 'Red Chilli Paste', 'Cashew Paste'],
                'Ready Masalas' => ['Chicken Masala', 'Paneer Masala', 'Biryani Masala', 'Sambar Powder', 'Chole Masala', 'Chaat Masala', 'Pav Bhaji Masala', 'Meat Masala', 'Fish Masala']
            ],
            'Snacks & Munchies' => [
                'Chips & Crisps' => ['Potato Chips', 'Nachos', 'Banana Chips', 'Popcorn', 'Tortilla Chips', 'Pringles', 'Veggie Chips'],
                'Biscuits & Cookies' => ['Glucose Biscuits', 'Marie Biscuits', 'Cream Biscuits', 'Cookies', 'Salted Crackers', 'Digestive Biscuits', 'Oat Cookies', 'Butter Cookies'],
                'Namkeen & Savouries' => ['Bhujia', 'Mixture', 'Peanuts', 'Chana Jor Garam', 'Moong Dal', 'Sev', 'Mathri', 'Chakli'],
                'Chocolates & Candies' => ['Milk Chocolate', 'Dark Chocolate', 'Wafer Chocolate', 'Toffees', 'Gummies', 'Lollipops', 'Mints', 'Chewing Gum']
            ],
            'Beverages' => [
                'Tea' => ['Leaf Tea', 'Dust Tea', 'Green Tea', 'Tea Bags', 'Masala Tea', 'Lemon Tea', 'Chamomile Tea', 'Earl Grey Tea'],
                'Coffee' => ['Instant Coffee', 'Filter Coffee', 'Ground Coffee', 'Coffee Beans', 'Cold Coffee Mix', 'Cappuccino Mix'],
                'Soft Drinks' => ['Cola', 'Orange Soda', 'Lemon Drink', 'Tonic Water', 'Ginger Ale', 'Club Soda', 'Diet Cola'],
                'Fruit Juices' => ['Apple Juice', 'Orange Juice', 'Mixed Fruit Juice', 'Mango Drink', 'Grape Juice', 'Pomegranate Juice', 'Cranberry Juice', 'Guava Juice'],
                'Health Drinks' => ['Energy Drink', 'Malt Drink', 'Protein Shake', 'Glucose Powder', 'Electrolyte Drink']
            ],
            'Breakfast & Instant Food' => [
                'Breakfast Cereals' => ['Corn Flakes', 'Oats', 'Muesli', 'Chocos', 'Granola', 'Wheat Flakes'],
                'Noodles & Pasta' => ['Instant Noodles', 'Hakka Noodles', 'Penne Pasta', 'Macaroni', 'Spaghetti', 'Fusilli', 'Cup Noodles'],
                'Ready to Cook' => ['Idli Batter', 'Dosa Batter', 'Instant Upma', 'Instant Poha', 'Instant Halwa', 'Pancake Mix'],
                'Sauces & Spreads' => ['Tomato Ketchup', 'Mayonnaise', 'Jam', 'Peanut Butter', 'Chocolate Spread', 'Schezwan Sauce', 'Soy Sauce', 'Chilli Sauce']
            ],
            'Personal Care' => [
                'Bath & Hand Wash' => ['Bathing Soap', 'Body Wash', 'Hand Wash', 'Shower Gel', 'Loofah'],
                'Hair Care' => ['Shampoo', 'Conditioner', 'Hair Oil', 'Hair Color', 'Hair Serum', 'Hair Gel'],
                'Skin Care' => ['Face Wash', 'Body Lotion', 'Face Cream', 'Sunscreen', 'Moisturizer', 'Face Scrub', 'Sheet Mask'],
                'Oral Care' => ['Toothpaste', 'Toothbrush', 'Mouthwash', 'Dental Floss'],
                'Deos & Perfumes' => ['Deodorant', 'Perfume', 'Body Mist', 'Roll On']
            ],
            'Home Care' => [
                'Detergents' => ['Washing Powder', 'Liquid Detergent', 'Fabric Conditioner', 'Stain Remover'],
                'Dishwashers' => ['Dishwash Bar', 'Dishwash Liquid', 'Scrub Pad', 'Steel Scrubber'],
                'Cleaners' => ['Floor Cleaner', 'Toilet Cleaner', 'Glass Cleaner', 'Kitchen Cleaner', 'Furniture Polish'],
                'Fresheners' => ['Air Freshener', 'Bathroom Freshener', 'Camphor', 'Naphthalene Balls']
            ],
            'Baby Care' => [
                'Diapers & Wipes' => ['Baby Diapers', 'Baby Wipes', 'Diaper Pants', 'Changing Mats'],
                'Baby Food' => ['Baby Cereal', 'Infant Formula', 'Baby Snacks', 'Fruit Puree'],
                'Baby Bath & Skin' => ['Baby Soap', 'Baby Shampoo', 'Baby Oil', 'Baby Lotion', 'Baby Powder', 'Baby Cream']
            ],
            'Meat, Fish & Eggs' => [
                'Chicken' => ['Chicken Curry Cut', 'Chicken Breast', 'Chicken Drumstick', 'Chicken Wings', 'Chicken Mince', 'Chicken Liver'],
                'Mutton' => ['Mutton Curry Cut', 'Mutton Chops', 'Mutton Mince', 'Mutton Liver'],
                'Fish & Seafood' => ['Rohu Fish', 'Catla Fish', 'Prawns', 'Salmon', 'Tuna', 'Sardines', 'Crab'],
                'Fresh Eggs' => ['Farm Fresh Eggs', 'Free Range Eggs']
            ],
            'Frozen Food' => [
                'Veg Frozen' => ['Green Peas', 'Sweet Corn', 'Mixed Vegetables', 'French Fries', 'Veg Nuggets', 'Hash Browns'],
                'Non-Veg Frozen' => ['Chicken Nuggets', 'Chicken Popcorn', 'Chicken Sausages', 'Fish Fingers', 'Prawns']
            ]
        ];

        $categoryColors = [
            'Fruits & Vegetables' => '10b981', // Green
            'Dairy, Bread & Eggs' => '3b82f6', // Blue
            'Atta, Rice & Dal' => 'f59e0b', // Amber
            'Masala & Spices' => 'ef4444', // Red
            'Snacks & Munchies' => 'f97316', // Orange
            'Beverages' => '06b6d4', // Cyan
            'Breakfast & Instant Food' => '8b5cf6', // Violet
            'Personal Care' => 'ec4899', // Pink
            'Home Care' => '6366f1', // Indigo
            'Baby Care' => '14b8a6', // Teal
            'Meat, Fish & Eggs' => 'be123c', // Rose
            'Frozen Food' => '0ea5e9', // Sky
        ];

        foreach ($catalog as $categoryName => $subCategories) {
            // Create Category
            $categoryImage = $categoryImages[$categoryName] ?? "https://loremflickr.com/600/400/" . urlencode(Str::slug($categoryName, ','));
            
            $category = Category::updateOrCreate(
                ['slug' => Str::slug($categoryName)],
                [
                    'name' => $categoryName,
                    'description' => 'Best quality ' . $categoryName . ' for your daily needs.',
                    'image' => $categoryImage,
                    'is_active' => true,
                ]
            );

            foreach ($subCategories as $subCategoryName => $products) {
                // Create SubCategory
                $subCategoryImage = $subCategoryImages[$subCategoryName] ?? "https://loremflickr.com/400/400/" . urlencode(Str::slug($subCategoryName, ','));
                
                $subCategory = SubCategory::updateOrCreate(
                    ['slug' => Str::slug($subCategoryName), 'category_id' => $category->id],
                    [
                        'name' => $subCategoryName,
                        'description' => 'Fresh and premium ' . $subCategoryName,
                        'image' => $subCategoryImage,
                        'is_active' => true,
                    ]
                );

                // Create Products
                foreach ($products as $productName) {
                    // Check if product exists to avoid duplicates
                    $exists = Product::where('sub_category_id', $subCategory->id)
                                    ->where('name', $productName)
                                    ->exists();
                    
                    if (!$exists) {
                        $productImage = $subCategoryImage; 
                        
                        // Determine unit based on category/subcategory
                        $unit = 'pc';
                        if (in_array($categoryName, ['Fruits & Vegetables', 'Meat, Fish & Eggs', 'Atta, Rice & Dal'])) {
                            $unit = 'kg';
                        } elseif ($categoryName === 'Beverages' || $subCategoryName === 'Milk & Curd') {
                            $unit = 'ltr';
                        } elseif (str_contains($productName, 'Bread') || str_contains($productName, 'Buns')) {
                            $unit = 'pack';
                        }

                        // Adjust price range based on category
                        $minPrice = 20;
                        $maxPrice = 200;
                        if ($categoryName === 'Meat, Fish & Eggs' || $categoryName === 'Personal Care') {
                            $minPrice = 100;
                            $maxPrice = 800;
                        } elseif ($categoryName === 'Home Care' || $categoryName === 'Baby Care') {
                            $minPrice = 150;
                            $maxPrice = 1200;
                        }

                        Product::factory()->create([
                            'category_id' => $category->id,
                            'sub_category_id' => $subCategory->id,
                            'name' => $productName,
                            'slug' => Str::slug($productName) . '-' . Str::random(5),
                            'price' => rand($minPrice, $maxPrice),
                            'stock' => rand(20, 200),
                            'unit' => $unit,
                            'image' => $productImage,
                            'is_active' => true,
                            'description' => "Premium quality $productName, carefully selected and packed to ensure the highest standards of freshness and quality for our SmartGrocery customers.",
                        ]);
                    }
                }
            }
        }
    }
}
