<?php

namespace Database\Seeders;

use App\Enums\PostStatus;
use App\Enums\PostType;
use App\Models\SocialPost;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Platform;
use App\Models\PostMetric;
use App\Models\Campaign;
use App\Models\Core\File;
use App\Models\SocialPostFile;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Faker\Factory as Faker;
use Carbon\Carbon;

class DemoPostSeeder extends Seeder
{
    /**
     * Run the database seeds for social posts.
     */
    public function run(): void
    {
        $faker = Faker::create();

        // Get all social accounts with their relationships
        $accounts = SocialAccount::with(['user', 'platform'])->get();

        if ($accounts->isEmpty()) {
            $this->command->warn('Please run DemoSocialAccountSeeder first!');
            return;
        }

        // Get available gallery images
        $galleryImages = File::where('type', \App\Enums\FileKey::GALLERY_FILE->value)
            ->whereHas('platforms')
            ->get();

        if ($galleryImages->isEmpty()) {
            $this->command->warn('No gallery images found. Please upload some images to the gallery first.');
            return;
        }

        $this->command->info('Found ' . $galleryImages->count() . ' gallery images to use.');

        // Create some campaigns first
        $campaigns = $this->createCampaigns();

        $postContents = [
            'promotional' => [
                "🎉 Big announcement coming soon! Stay tuned for something amazing! #ComingSoon #Excited",
                "Transform your business with our innovative solutions 🚀 Learn more at our website! #Innovation #BusinessGrowth",
                "Limited time offer! 50% off on all products this weekend only! 🛍️ #Sale #WeekendDeals",
                "Join thousands of satisfied customers who made the switch! ⭐ #CustomerSuccess #Testimonial",
                "New product launch! 🎊 Be the first to experience the future. Pre-order now! #NewProduct #Launch",
            ],
            'educational' => [
                "5 tips to boost your productivity today: 1. Start with the hardest task 2. Take regular breaks... 📚 #ProductivityTips",
                "Did you know? 🤔 The average person spends 2.5 hours on social media daily! #Facts #SocialMedia",
                "How to master any skill in 30 days - Thread 🧵 #Learning #SkillDevelopment",
                "Common mistakes to avoid when starting your business journey 💡 #Entrepreneurship #BusinessTips",
                "The science behind morning routines and why they work ☀️ #MorningRoutine #Science",
            ],
            'engagement' => [
                "What's your favorite feature? Comment below! 👇 #Community #Engagement",
                "Tag a friend who needs to see this! 🏷️ #TagAFriend #Share",
                "Poll: Which design do you prefer? A or B? Vote now! 📊 #Poll #YourOpinion",
                "Share your success story with us! We'd love to feature you 🌟 #SuccessStory #Community",
                "Caption this photo! Best caption wins a prize 🎁 #Contest #Fun",
            ],
            'inspirational' => [
                "Your only limit is you 💪 Keep pushing forward! #Motivation #MondayMotivation",
                "Success is not final, failure is not fatal. It's the courage to continue that counts 🌟 #Inspiration",
                "Dream big, work hard, stay focused 🎯 #Goals #Success",
                "Every expert was once a beginner. Keep learning! 📈 #GrowthMindset #Learning",
                "The best time to start was yesterday. The next best time is now! ⏰ #TakeAction #StartToday",
            ],
            'news' => [
                "Breaking: Major update released! Check out all the new features 📰 #News #Update",
                "Industry report: Latest trends and insights for 2024 📊 #IndustryNews #Trends",
                "We're hiring! Join our growing team 🚀 #Hiring #Careers",
                "Partnership announcement: Excited to work with @partner 🤝 #Partnership #Collaboration",
                "Milestone achieved: 1 million users! Thank you for your support 🎉 #Milestone #ThankYou",
            ],
        ];

        $postCounter = 0;
        $metricsCounter = 0;

        // Generate posts for current month (September 2025) and next month (October 2025)
        $now = now(); // 2025-09-13
        $demoDates = [];

        // Current month (September 2025) - from today onwards
        $currentMonth = $now->copy()->startOfMonth(); // 2025-09-01
        $endOfCurrentMonth = $now->copy()->endOfMonth(); // 2025-09-30

        // Next month (October 2025)
        $startOfNextMonth = $now->copy()->addMonth()->startOfMonth(); // 2025-10-01
        $endOfNextMonth = $now->copy()->addMonth()->endOfMonth(); // 2025-10-31

        // Create strategic dates with at least 4 posts each
        $strategicDates = [
            // Current month key dates
            '2025-09-13' => 8,  // Today - 8 posts (2 full rows)
            '2025-09-14' => 4,  // Tomorrow - 4 posts (1 full row)
            '2025-09-15' => 8,  // Weekend - 8 posts (2 full rows)
            '2025-09-16' => 4,  // Weekend - 4 posts (1 full row)
            '2025-09-18' => 8,  // Monday - 8 posts (2 full rows)
            '2025-09-20' => 4,  // Wednesday - 4 posts (1 full row)
            '2025-09-22' => 8,  // Friday - 8 posts (2 full rows)
            '2025-09-25' => 4,  // Next week - 4 posts (1 full row)
            '2025-09-27' => 8,  // Weekend prep - 8 posts (2 full rows)
            '2025-09-30' => 4,  // End of month - 4 posts (1 full row)

            // Next month key dates
            '2025-10-01' => 8,  // Start of October - 8 posts (2 full rows)
            '2025-10-03' => 4,  // Thursday - 4 posts (1 full row)
            '2025-10-05' => 8,  // Weekend - 8 posts (2 full rows)
            '2025-10-08' => 4,  // Monday - 4 posts (1 full row)
            '2025-10-10' => 8,  // Wednesday - 8 posts (2 full rows)
            '2025-10-12' => 4,  // Weekend - 4 posts (1 full row)
            '2025-10-15' => 8,  // Mid month - 8 posts (2 full rows)
            '2025-10-18' => 4,  // Friday - 4 posts (1 full row)
            '2025-10-20' => 8,  // Weekend - 8 posts (2 full rows)
            '2025-10-22' => 4,  // Monday - 4 posts (1 full row)
            '2025-10-25' => 8,  // Friday - 8 posts (2 full rows)
            '2025-10-27' => 4,  // Weekend - 4 posts (1 full row)
            '2025-10-30' => 8,  // End of month - 8 posts (2 full rows)
            '2025-10-31' => 4,  // Halloween - 4 posts (1 full row)
        ];

        // Convert to the format expected by the rest of the code
        foreach ($strategicDates as $dateStr => $count) {
            $demoDates[$dateStr] = [
                'count' => $count,
                'time' => Carbon::parse($dateStr)
            ];
        }

        // First, create demo posts for specific dates
        $accountIndex = 0;
        $accountsArray = $accounts->toArray();
        $totalAccounts = count($accountsArray);

        foreach ($demoDates as $date => $dateInfo) {
            for ($i = 0; $i < $dateInfo['count']; $i++) {
                $account = $accountsArray[$accountIndex % $totalAccounts];
                $accountIndex++;
                $postCounter++;

                $category = $faker->randomElement(array_keys($postContents));
                $content = $faker->randomElement($postContents[$category]);

                // Add some variety to content
                if ($faker->boolean(50)) {
                    $content .= "\n\n" . $faker->url;
                }

                // Determine post status based on date
                $postDate = $dateInfo['time'];
                $isScheduled = $postDate->isFuture();
                $isDraft = $faker->boolean(15); // Lower chance for demo posts
                $status = $this->determinePostStatus($isScheduled, $isDraft, $faker);

                // Set specific times for demo posts
                $scheduleTime = $isScheduled ? $postDate->copy()->addHours($faker->numberBetween(9, 17))->addMinutes($faker->numberBetween(0, 59)) : null;
                $postedAt = ($status === PostStatus::SUCCESS->value && !$isScheduled) ? $postDate->copy()->addHours($faker->numberBetween(9, 17))->addMinutes($faker->numberBetween(0, 59)) : null;

                $post = SocialPost::create([
                    'uid' => Str::uuid(),
                    'user_id' => $account['user_id'],
                    'account_id' => $account['id'],
                    'platform_id' => $account['platform_id'],
                    'campaign_id' => $faker->boolean(40) ? $faker->randomElement($campaigns)->id : null,
                    'content' => $content,
                    'link' => $faker->boolean(60) ? $faker->url : null,
                    'is_scheduled' => $isScheduled,
                    'schedule_time' => $scheduleTime,
                    'repeat_every' => $faker->randomElement([1440, 2880, 10080]),
                    'repeat_schedule_end_date' => $isScheduled ? $faker->dateTimeBetween($postDate->copy()->addMonth(), '+6 months') : null,
                    'is_draft' => $isDraft,
                    'post_type' => $this->getPostTypeForPlatform($account['platform']['slug']),
                    'status' => $status,
                    'platform_response' => $status === PostStatus::SUCCESS->value ? json_encode(['id' => $faker->uuid, 'url' => $faker->url]) : null,
                    'posted_at' => $postedAt,
                    'platform_post_id' => $status === PostStatus::SUCCESS->value ? $faker->uuid : null,
                    'post_url' => $status === PostStatus::SUCCESS->value ? $faker->url : null,
                    'created_at' => $postDate,
                    'updated_at' => now(),
                ]);

                // Attach random gallery images to all posts
                if ($galleryImages->isNotEmpty()) {
                    $numberOfImages = $faker->numberBetween(1, min(3, $galleryImages->count()));
                    $selectedImages = $galleryImages->random($numberOfImages);

                    foreach ($selectedImages as $image) {
                        SocialPostFile::create([
                            'social_post_id' => $post->id,
                            'file_id' => $image->id,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }

                // Create metrics for successful posts
                if ($status === PostStatus::SUCCESS->value && $faker->boolean(80)) {
                    $metricsCounter++;
                    $this->createPostMetrics($post, $account['followers'] ?? 1000);
                }
            }
        }


        $this->command->info("Created {$postCounter} demo posts with {$metricsCounter} metrics!");
        $this->command->info("Posts created for September 2025 and October 2025 with gallery images!");
        $this->command->info("All dates have minimum 4 posts for perfect grid display!");
    }

    /**
     * Create demo campaigns
     */
    private function createCampaigns(): \Illuminate\Support\Collection
    {
        $faker = Faker::create();
        $users = User::all();
        $campaigns = collect();

        $campaignNames = [
            'Summer Sale 2024',
            'Product Launch Campaign',
            'Brand Awareness Drive',
            'Holiday Season Promotion',
            'Q1 Marketing Campaign',
            'Customer Engagement Series',
            'Educational Content Month',
            'Year End Celebration',
            'New Feature Rollout',
            'Community Building Initiative',
        ];

        foreach ($campaignNames as $name) {
            $user = $users->random();
            $now = now();
            $currentMonth = $now->copy()->startOfMonth();
            $startDate = $faker->dateTimeBetween($currentMonth, $now->copy()->addDays(30));

            $campaign = Campaign::create([
                'uid' => Str::uuid(),
                'user_id' => $user->id,
                'workspace_id' => $user->current_workspace_id,
                'name' => $name,
                'description' => $faker->paragraph(3),
                'start_date' => $startDate,
                'end_date' => $faker->dateTimeBetween($startDate, $now->copy()->addMonths(3)),
                'repeat_every' => $faker->randomElement([1440, 2880, 10080]), // Daily, 2 days, weekly
                'repeat_end_date' => $faker->dateTimeBetween($now->copy()->addMonth(), $now->copy()->addMonths(6)),
                'status' => $faker->randomElement(['0', '1']),
                'created_at' => $faker->dateTimeBetween($currentMonth, $now),
                'updated_at' => now(),
            ]);

            $campaigns->push($campaign);
        }

        return $campaigns;
    }

    /**
     * Determine post status based on conditions
     */
    private function determinePostStatus($isScheduled, $isDraft, $faker): int
    {
        if ($isDraft) {
            return PostStatus::PENDING->value;
        }
        if ($isScheduled) {
            return PostStatus::SCHEDULE->value;
        }

        return $faker->randomElement([
            PostStatus::SUCCESS->value,
            PostStatus::SUCCESS->value,
            PostStatus::SUCCESS->value, // More weight to successful posts
            PostStatus::FAILED->value,
            PostStatus::PENDING->value,
        ]);
    }

    /**
     * Get appropriate post type for platform
     */
    private function getPostTypeForPlatform(string $platform): int
    {
        $faker = Faker::create();

        $platformTypes = [
            'facebook' => [PostType::FEED->value, PostType::STORY->value],
            'instagram' => [PostType::FEED->value, PostType::REELS->value, PostType::STORY->value],
            'twitter' => [PostType::FEED->value],
            'linkedin' => [PostType::FEED->value],
            'youtube' => [PostType::FEED->value, PostType::SHORTS->value],
            'pinterest' => [PostType::FEED->value],
            'tiktok' => [PostType::REELS->value, PostType::STORY->value],
            'reddit' => [PostType::FEED->value],
            'whatsapp' => [PostType::FEED->value],
            'telegram' => [PostType::FEED->value],
        ];

        $types = $platformTypes[$platform] ?? [PostType::FEED->value];
        return $faker->randomElement($types);
    }

    /**
     * Create post metrics
     */
    private function createPostMetrics($post, $followers): void
    {
        $faker = Faker::create();

        // Calculate realistic metrics based on followers
        $engagementRate = $faker->randomFloat(2, 0.5, 15.0) / 100;
        $reach = (int)($followers * $faker->randomFloat(2, 0.1, 1.5));
        $impressions = (int)($reach * $faker->randomFloat(2, 1.1, 3.0));
        $engagements = (int)($reach * $engagementRate);

        PostMetric::create([
            'post_id' => $post->id,
            'impressions' => $impressions,
            'engagements' => $engagements,
            'reactions' => (int)($engagements * 0.4),
            'comments' => (int)($engagements * 0.2),
            'shares' => (int)($engagements * 0.1),
            'likes' => (int)($engagements * 0.3),
            'reach' => $reach,
            'created_at' => $post->created_at,
            'updated_at' => now(),
        ]);
    }
}