<?php

namespace App\Http\Controllers;

use App\Models\Topic;
use App\Models\TopicCategory;
use App\Models\TopicTag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class ForumController extends Controller
{
    /**
     * Display the forum index page.
     */
    public function index(): Response
    {
        $topics = Topic::with(['user', 'categories', 'tags', 'comments'])
            ->where('status', 'published')
            ->orderBy('is_pinned', 'desc')
            ->orderBy('last_activity_at', 'desc')
            ->paginate(20);

        $categories = TopicCategory::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $tags = TopicTag::orderBy('usage_count', 'desc')
            ->limit(50)
            ->get();

        $user = null;
        if (Auth::check()) {
            $user = Auth::user();
            $user->loadCount(['topics' => function ($query) {
                $query->where('status', 'published');
            }, 'topicComments']);
        }

        return Inertia::render('mattock/Forum', [
            'topics'     => $topics,
            'categories' => $categories,
            'tags'       => $tags,
        ]);
    }
	
    /**
     * Display all forum categories.
     */
    public function categories(): Response
    {
        $categories = TopicCategory::where('is_active', true)
            ->withCount(['topics' => function ($query) {
                $query->where('status', 'published');
            }])
            ->with(['topics' => function ($query) {
                $query->where('status', 'published')
                    ->latest()
                    ->limit(5);
            }])
            ->orderBy('sort_order')
            ->get();

        // Get total statistics
        $totalTopics = Topic::where('status', 'published')->count();
        $totalComments = \App\Models\TopicComment::where('is_approved', true)->count();
        
        // Get trending topics (most viewed in last 7 days)
        $trendingTopics = Topic::where('status', 'published')
            ->where('created_at', '>=', now()->subDays(7))
            ->orderBy('view_count', 'desc')
            ->with(['user', 'categories'])
            ->limit(5)
            ->get();

        // Get recently resolved topics
        $resolvedTopics = Topic::where('status', 'resolved')
            ->with(['user', 'categories'])
            ->latest()
            ->limit(5)
            ->get();

        return Inertia::render('mattock/ForumCategories', [
            'categories' => $categories,
            'totalCategories' => $categories->count(),
            'totalTopics' => $totalTopics,
            'totalComments' => $totalComments,
            'trendingTopics' => $trendingTopics,
            'resolvedTopics' => $resolvedTopics,
        ]);
    }
	
	/*public function categoryShow(string $slug): Response
	{
		$topics = Topic::with(['user', 'categories', 'tags', 'comments'])
			->where('status', 'published')
			->orderBy('is_pinned', 'desc')
			->orderBy('last_activity_at', 'desc')
			->paginate(20);
		
		$categories = TopicCategory::where('is_active', true)
			->orderBy('sort_order')
			->get();
		
		$tags = TopicTag::orderBy('usage_count', 'desc')
			->limit(50)
			->get();
		
		$user = null;
		if (Auth::check()) {
			$user = Auth::user();
			$user->loadCount(['topics' => function ($query) {
				$query->where('status', 'published');
			}, 'topicComments']);
		}
		
		return Inertia::render('mattock/ForumCategoryDetail', [
			'topics'     => $topics,
			'categories' => $categories,
			'tags'       => $tags,
		]);
	}*/

    /**
     * Show the form for creating a new topic.
     */
    public function create(): Response
    {
        $categories = TopicCategory::where('is_active', true)
            ->orderBy('sort_order')
            ->get(['id', 'name', 'slug']);

        $tags = TopicTag::orderBy('name')
            ->get(['id', 'name', 'slug']);

        return Inertia::render('mattock/ForumCreate', [
            'categories' => $categories,
            'tags'       => $tags,
        ]);
    }

    /**
     * Store a newly created topic in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'              => 'required|string|min:10|max:200',
            'content'            => 'required|string|min:20|max:5000',
            'category_ids'       => 'required|array|min:1',
            'category_ids.*'     => 'exists:topic_categories,id',
            'tag_ids'            => 'array',
            'tag_ids.*'          => 'exists:topic_tags,id',
            'priority'           => 'required|in:normal,urgent',
            'comment_permission' => 'required|in:all,experts_only,users_only,closed',
        ]);

        // Generate unique slug
        $slug = $this->generateUniqueSlug($validated['title']);

        // Create topic
        $topic = Topic::create([
            'title'              => $validated['title'],
            'slug'               => $slug,
            'short_description'  => Str::limit(strip_tags($validated['content']), 100),
            'content'            => $validated['content'],
            'user_id'            => Auth::id(),
            'status'             => 'published', // Automatically publish as requested
            'priority'           => $validated['priority'],
            'comment_permission' => $validated['comment_permission'],
            'view_count'         => 0,
            'like_count'         => 0,
            'comment_count'      => 0,
            'is_featured'        => false,
            'is_pinned'          => false,
            'last_activity_at'   => now(),
        ]);

        // Attach categories
        $topic->categories()->attach($validated['category_ids']);

        // Attach tags if provided
        if (! empty($validated['tag_ids'])) {
            $topic->tags()->attach($validated['tag_ids']);

            // Update tag usage count
            TopicTag::whereIn('id', $validated['tag_ids'])
                ->increment('usage_count');
        }

        return redirect()->route('forum.show', $topic->slug)
            ->with('message', 'Topic đã được tạo và xuất bản thành công!');
    }

    /**
     * Display the specified topic.
     */
    public function show(string $slug): Response
    {
        $topic = Topic::where('slug', $slug)
            ->with([
                'user',
                'categories',
                'tags',
                'comments' => function ($query) {
                    $query->with('user')
                        ->where('is_approved', true)
                        ->orderBy('created_at', 'asc');
                },
            ])
            ->firstOrFail();

        // Increment view count
        $topic->increment('view_count');

        return Inertia::render('mattock/ForumShow', [
            'topic' => $topic,
        ]);
    }

    /**
     * Generate a unique slug for the topic.
     */
    private function generateUniqueSlug(string $title): string
    {
        $baseSlug = Str::slug($title);

        // If the slug is empty (e.g., non-Latin characters), use a fallback
        if (empty($baseSlug)) {
            $baseSlug = 'topic-' . time();
        }

        $slug = $baseSlug;
        $counter = 1;

        // Check for uniqueness and append number if needed
        while (Topic::where('slug', $slug)->exists()) {
            $slug = $baseSlug . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

    /**
     * Create a new category via AJAX.
     */
    public function createCategory(Request $request)
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:50|unique:topic_categories,name',
            'description' => 'nullable|string|max:200',
            'color'       => 'required|string|regex:/^#[A-Fa-f0-9]{6}$/',
        ]);

        $category = TopicCategory::create([
            'name'        => $validated['name'],
            'slug'        => Str::slug($validated['name']),
            'description' => $validated['description'],
            'color'       => $validated['color'],
            'sort_order'  => TopicCategory::max('sort_order') + 1,
            'is_active'   => true,
        ]);

        return response()->json([
            'success'  => true,
            'category' => $category->only(['id', 'name', 'slug']),
            'message'  => 'Category đã được tạo thành công!',
        ]);
    }

    /**
     * Create a new tag via AJAX.
     */
    public function createTag(Request $request)
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:30|unique:topic_tags,name',
            'description' => 'nullable|string|max:200',
            'color'       => 'required|string|regex:/^#[A-Fa-f0-9]{6}$/',
        ]);

        $tag = TopicTag::create([
            'name'        => $validated['name'],
            'slug'        => Str::slug($validated['name']),
            'description' => $validated['description'],
            'color'       => $validated['color'],
            'usage_count' => 0,
        ]);

        return response()->json([
            'success' => true,
            'tag'     => $tag->only(['id', 'name', 'slug']),
            'message' => 'Tag đã được tạo thành công!',
        ]);
    }

    /**
     * Show topics by category slug.
     */
    public function categoryShow(string $slug): Response
    {
        // Get category by slug
        $category = TopicCategory::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        // Get topics in this category
        $topics = Topic::with(['user', 'categories', 'tags', 'comments'])
            ->whereHas('categories', function ($query) use ($category) {
                $query->where('topic_categories.id', $category->id);
            })
            ->where('status', 'published')
            ->orderBy('is_pinned', 'desc')
            ->orderBy('last_activity_at', 'desc')
            ->paginate(20);

        // Get other categories for sidebar
        $categories = TopicCategory::where('is_active', true)
            ->where('id', '!=', $category->id)
            ->withCount(['topics' => function ($query) {
                $query->where('status', 'published');
            }])
            ->orderBy('sort_order')
            ->limit(10)
            ->get();

        // Get popular tags
        $tags = TopicTag::orderBy('usage_count', 'desc')
            ->limit(30)
            ->get();

        // Get statistics for this category
        $totalTopics = Topic::whereHas('categories', function ($query) use ($category) {
            $query->where('topic_categories.id', $category->id);
        })->where('status', 'published')->count();

        $totalComments = \App\Models\TopicComment::whereHas('topic', function ($query) use ($category) {
            $query->whereHas('categories', function ($q) use ($category) {
                $q->where('topic_categories.id', $category->id);
            });
        })->where('is_approved', true)->count();

        return Inertia::render('mattock/ForumCategoryDetail', [
            'category' => $category,
            'topics' => $topics,
            'categories' => $categories,
            'tags' => $tags,
            'totalTopics' => $totalTopics,
            'totalComments' => $totalComments,
        ]);
    }

    /**
     * Show user's own topics.
     */
    public function userPosts(): Response
    {
        $topics = Topic::with(['user', 'categories', 'tags', 'comments'])
            ->where('user_id', Auth::id())
            ->where('status', 'published')
            ->orderBy('is_pinned', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        $user = Auth::user();
        $user->loadCount(['topics' => function ($query) {
            $query->where('status', 'published');
        }, 'topicComments']);

        return Inertia::render('mattock/ForumUserPosts', [
            'topics' => $topics,
            'user'   => $user,
        ]);
    }

    /**
     * Show topics where user has commented.
     */
    public function userCommented(): Response
    {
        $topicIds = Auth::user()->topicComments()
            ->where('is_approved', true)
            ->distinct()
            ->pluck('topic_id');

        $topics = Topic::with(['user', 'categories', 'tags', 'comments'])
            ->whereIn('id', $topicIds)
            ->where('status', 'published')
            ->orderBy('last_activity_at', 'desc')
            ->paginate(10);

        $user = Auth::user();
        $user->loadCount(['topics' => function ($query) {
            $query->where('status', 'published');
        }, 'topicComments']);

        return Inertia::render('mattock/ForumUserCommented', [
            'topics' => $topics,
            'user'   => $user,
        ]);
    }

    /**
     * Show topics user is following (placeholder - requires follow system).
     */
    public function userFollowing(): Response
    {
        // For now, return empty collection as follow system isn't implemented yet
        $topics = collect([]);

        $user = Auth::user();
        $user->loadCount(['topics' => function ($query) {
            $query->where('status', 'published');
        }, 'topicComments']);

        return Inertia::render('mattock/ForumUserFollowing', [
            'topics' => $topics,
            'user'   => $user,
        ]);
    }
}
