<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Models\ContentIdea;
use App\Models\Campaign;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class ContentIdeaController extends Controller
{
    /**
     * Display a listing of content ideas.
     */
    public function index()
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        $contentIdeas = ContentIdea::where('brand_id', $brand->id)
            ->with(['campaign', 'user'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('brand.content-ideas.index', compact('contentIdeas'));
    }

    /**
     * Show the form for generating content ideas.
     */
    public function create()
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        // Get campaigns for this brand
        $campaigns = Campaign::where('brand_id', $brand->id)
            ->orderBy('name')
            ->get();

        return view('brand.content-ideas.create', compact('campaigns'));
    }

    /**
     * Store a newly created content idea request.
     */
    public function store(Request $request)
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        // Validate request
        $request->validate([
            'topic' => 'required|string|max:255',
            'platform' => 'required|string|max:50',
            'target_audience' => 'required|string|max:255',
            'campaign_goals' => 'required|string|max:500',
            'tone' => 'required|string|max:50',
            'number_of_ideas' => 'required|integer|min:1|max:20',
            'campaign_id' => 'nullable|exists:campaigns,id,brand_id,' . $brand->id,
        ]);

        // Create AI job for content idea generation
        $aiJob = \App\Models\AiJob::create([
            'job_id' => (string) Str::uuid(),
            'type' => 'content_idea_generation',
            'status' => 'queued',
            'brand_id' => $brand->id,
            'creator_id' => null,
            'proposal_id' => null,
            'result_text' => null,
            'result_meta' => null,
            'provider' => null,
            'error_message' => null,
            'token_usage' => 0,
        ]);

        // Prepare payload for AI processing
        $payload = [
            'topic' => $request->topic,
            'platform' => $request->platform,
            'target_audience' => $request->target_audience,
            'campaign_goals' => $request->campaign_goals,
            'tone' => $request->tone,
            'number_of_ideas' => $request->number_of_ideas,
            'brand_name' => $brand->name,
            'brand_industry' => $brand->settings['industry'] ?? 'general',
        ];

        // Dispatch job to process the content idea generation
        \App\Jobs\GenerateContentIdeasJob::dispatch($aiJob->id, $payload);

        return redirect()->route('brand.content-ideas.index')
            ->with('success', 'Content ideas generation started! Check back soon for results.');
    }

    /**
     * Save a content idea to draft.
     */
    public function saveToDraft($id)
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        $contentIdea = ContentIdea::findOrFail($id);

        // Check if content idea belongs to the same brand
        if ($contentIdea->brand_id !== $brand->id) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }

        // Update status to draft
        $contentIdea->update(['status' => 'draft']);

        return redirect()->back()->with('success', 'Content idea saved to draft!');
    }

    /**
     * Copy a content idea.
     */
    public function copy($id)
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        $contentIdea = ContentIdea::findOrFail($id);

        // Check if content idea belongs to the same brand
        if ($contentIdea->brand_id !== $brand->id) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }

        // Return the content idea data as JSON for copying
        return response()->json([
            'caption' => $contentIdea->caption,
            'hashtags' => $contentIdea->hashtags,
            'creative_hints' => $contentIdea->creative_hints,
        ]);
    }

    /**
     * Schedule a content idea as a post.
     */
    public function schedulePost($id, Request $request)
    {
        $brand = Auth::user()->brand;
        if (!$brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }

        $contentIdea = ContentIdea::findOrFail($id);

        // Check if content idea belongs to the same brand
        if ($contentIdea->brand_id !== $brand->id) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }

        // Validate scheduling request
        $request->validate([
            'scheduled_at' => 'required|date',
            'timezone' => 'required|string|timezone',
        ]);

        // Create a scheduled reel from the content idea
        $scheduledReel = \App\Models\ScheduledReel::create([
            'owner_id' => $brand->id,
            'owner_type' => 'App\Models\Brand',
            'template' => 'content_idea',
            'options' => [
                'caption' => $contentIdea->caption,
                'hashtags' => $contentIdea->hashtags,
                'creative_hints' => $contentIdea->creative_hints,
            ],
            'source_inputs' => [], // No source inputs for content ideas
            'scheduled_at' => $request->scheduled_at,
            'timezone' => $request->timezone,
            'status' => 'scheduled',
            'created_by' => Auth::id(),
        ]);

        // Update content idea status to scheduled
        $contentIdea->update(['status' => 'scheduled']);

        return redirect()->back()->with('success', 'Content idea scheduled successfully!');
    }
}