<?php

namespace App\Http\Controllers\Admin\Game;

use App\Http\Controllers\Controller;
use App\Models\HexlingBadge;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HexlingBadgeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Add New Badge'),
                'icon' => 'ph ph-plus-bold',
                'type' => 'link',
                'link' => route('admin.games.badges.create'),
            ],
        ];

        $badges = ModalIndexQuey::get(model: HexlingBadge::query());

        $columns = [
            [
                'label' => __('Badge Name'),
                'key' => 'badge_name',
                'is_sortable' => true,
            ],
            [
                'label' => __('Description'),
                'key' => 'badge_description',
                'render' => function ($badge) {
                    return '<span class="text-gray-600">'.($badge->badge_description ?: __('No description')).'</span>';
                },
            ],
            [
                'label' => __('Points'),
                'key' => 'badge_points',
                'is_sortable' => true,
                'render' => function ($badge) {
                    return '<span class="font-medium text-green-600">'.$badge->badge_points.' pts</span>';
                },
            ],
            [
                'label' => __('Order'),
                'key' => 'badge_order',
                'is_sortable' => true,
                'render' => function ($badge) {
                    return '<span class="badge badge-primary">'.$badge->badge_order.'</span>';
                },
            ],
            [
                'label' => __('Used in Games'),
                'render' => function ($badge) {
                    $gameCount = $badge->words()->count();

                    return '<span class="badge '.($gameCount > 0 ? 'badge-success' : 'badge-secondary').'">'.$gameCount.' games</span>';
                },
            ],
            [
                'label' => __('Image'),
                'render' => function ($badge) {
                    if ($badge->badge_image) {
                        return '<img src="'.$badge->badge_image.'" alt="'.$badge->badge_name.'" class="w-10 h-10 rounded-full object-cover">';
                    }

                    return '<div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
                                <span class="text-gray-500 text-xs">No image</span>
                            </div>';
                },
            ],
            [
                'label' => __('Action'),
                'render' => function ($badge) {
                    $action_buttons = [
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'link',
                            'href' => route('admin.games.badges.edit', $badge->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.games.badges.destroy', $badge->id),
                        ],
                    ];

                    return view('admin.components.table-action', compact('action_buttons'))->render();
                },
            ],
        ];

        return view('admin.pages.game.badges.index', compact('badges', 'columns', 'buttons'));
    }

    public function create()
    {
        adminUserHasPermission(permission: 'create');

        $buttons = [
            [
                'label' => __('Back to Badges'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.games.badges.index'),
            ],
        ];

        // Get the next available badge order
        $nextOrder = HexlingBadge::max('badge_order') + 1;

        return view('admin.pages.game.badges.create', compact('buttons', 'nextOrder'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        adminUserHasPermission(permission: 'create');

        $validated = $request->validate([
            'badge_name' => 'required|string|max:255|unique:hexling_badges,badge_name',
            'badge_description' => 'nullable|string|max:500',
            'badge_points' => 'required|integer|min:1|max:1000',
            'badge_order' => 'required|integer|min:0',
            'badge_image' => 'nullable|string',
        ]);

        HexlingBadge::create($validated);

        return response()->json([
            'message' => __('Badge created successfully'),
            'redirect' => route('admin.games.badges.index'),
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(HexlingBadge $badge)
    {
        adminUserHasPermission(permission: 'delete');

        // Check if badge is used in any games
        if ($badge->words()->count() > 0) {
            return response()->json([
                'message' => __('Cannot delete badge. It is being used in one or more games.'),
            ], 422);
        }

        $badge->delete();

        return response()->json([
            'message' => __('Badge was successfully deleted'),
            'reload' => true,
        ]);
    }

    public function edit(HexlingBadge $badge)
    {
        adminUserHasPermission(permission: 'edit');

        $buttons = [
            [
                'label' => __('Back to Badges'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.games.badges.index'),
            ],
        ];

        return view('admin.pages.game.badges.edit', compact('badge', 'buttons'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, HexlingBadge $badge)
    {
        adminUserHasPermission(permission: 'edit');

        $validated = $request->validate([
            'badge_name' => 'required|string|max:255|unique:hexling_badges,badge_name,'.$badge->id,
            'badge_description' => 'nullable|string|max:500',
            'badge_points' => 'required|integer|min:1|max:1000',
            'badge_order' => 'required|integer|min:0',
            'badge_image' => 'nullable|string',
        ]);

        $badge->update($validated);

        return response()->json([
            'message' => __('Badge was successfully updated'),
            'redirect' => route('admin.games.badges.index'),
        ]);
    }

    /**
     * Reorder badges
     */
    public function reorder(Request $request)
    {
        adminUserHasPermission(permission: 'edit');

        $request->validate([
            'badges' => 'required|array',
            'badges.*.id' => 'required|exists:hexling_badges,id',
            'badges.*.order' => 'required|integer|min:0',
        ]);

        try {
            DB::beginTransaction();

            foreach ($request->badges as $badgeData) {
                HexlingBadge::where('id', $badgeData['id'])->update([
                    'badge_order' => $badgeData['order'],
                ]);
            }

            DB::commit();

            return response()->json([
                'message' => __('Badges order updated successfully'),
            ]);

        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
