<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TopicTag;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class ForumTagController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $search = $request->input('search');
        $perPage = $request->input('per_page', 10);

        $tags = TopicTag::withCount('topics')
            ->when($search, function ($query, $search) {
                return $query->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            })
            ->orderBy('usage_count', 'desc')
            ->orderBy('name')
            ->paginate($perPage);

        return Inertia::render('admin/forum/tags/Index', [
            'tags' => $tags,
            'filters' => [
                'search' => $search,
                'per_page' => $perPage,
            ],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('admin/forum/tags/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:topic_tags',
            'slug' => 'nullable|string|max:255|unique:topic_tags',
            'description' => 'nullable|string',
            'color' => 'required|string|size:7|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        TopicTag::create($validated);

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tag created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(TopicTag $tag)
    {
        $tag->loadCount('topics');
        $topics = $tag->topics()
            ->with(['user', 'categories'])
            ->latest()
            ->paginate(10);

        return Inertia::render('admin/forum/tags/Show', [
            'tag' => $tag,
            'topics' => $topics,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(TopicTag $tag)
    {
        return Inertia::render('admin/forum/tags/Edit', [
            'tag' => $tag,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, TopicTag $tag)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:topic_tags,name,' . $tag->id,
            'slug' => 'nullable|string|max:255|unique:topic_tags,slug,' . $tag->id,
            'description' => 'nullable|string',
            'color' => 'required|string|size:7|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        $tag->update($validated);

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tag updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TopicTag $tag)
    {
        // Check if tag is being used
        if ($tag->usage_count > 0) {
            return back()->withErrors(['delete' => 'Cannot delete tag that is being used.']);
        }

        $tag->delete();

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tag deleted successfully.');
    }

    /**
     * Restore the specified resource.
     */
    public function restore($id)
    {
        $tag = TopicTag::withTrashed()->findOrFail($id);
        $tag->restore();

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tag restored successfully.');
    }

    /**
     * Permanently delete the specified resource.
     */
    public function forceDelete($id)
    {
        $tag = TopicTag::withTrashed()->findOrFail($id);
        $tag->forceDelete();

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tag permanently deleted.');
    }

    /**
     * Merge one tag into another
     */
    public function merge(Request $request, TopicTag $tag)
    {
        $validated = $request->validate([
            'target_tag_id' => 'required|exists:topic_tags,id|different:' . $tag->id,
        ]);

        $targetTag = TopicTag::find($validated['target_tag_id']);

        // Move all topics from source tag to target tag
        $topicIds = $tag->topics()->pluck('topics.id');
        foreach ($topicIds as $topicId) {
            // Check if the topic already has the target tag
            if (!$targetTag->topics()->where('topics.id', $topicId)->exists()) {
                $targetTag->topics()->attach($topicId);
            }
            $tag->topics()->detach($topicId);
        }

        // Update usage count
        $targetTag->increment('usage_count', $tag->usage_count);
        $tag->update(['usage_count' => 0]);

        // Delete the source tag
        $tag->delete();

        return redirect()->route('admin.forum.tags.index')
            ->with('success', 'Tags merged successfully.');
    }
}