<?php

namespace App\Http\Controllers\Admin\Game;

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

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

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

        $tab_buttons = [
            [
                'label' => __('All Hexling Games'),
                'link' => route('admin.games.hexling.index'),
            ],
            [
                'label' => __('Active Games'),
                'count' => HexlingWord::where('status', GameEnum::ACTIVE)->count(),
                'link' => route('admin.games.hexling.index', ['status' => 'active']),
            ],
            [
                'label' => __('Inactive Games'),
                'count' => HexlingWord::where('status', GameEnum::INACTIVE)->count(),
                'link' => route('admin.games.hexling.index', ['status' => 'inactive']),
            ],
        ];

        $hexlingGames = ModalIndexQuey::get(model: HexlingWord::query()
            ->when(request('status'), function ($query, $status) {
                if ($status === 'active') {
                    $query->where('status', GameEnum::ACTIVE);
                } elseif ($status === 'inactive') {
                    $query->where('status', GameEnum::INACTIVE);
                }
            })
            ->when(request('custom_start_date') && request('custom_end_date'), function ($query) {
                $query->whereBetween('game_date', [request('custom_start_date'), request('custom_end_date')]);
            })
            ->orderBy('game_date', 'desc'),
            with: ['players', 'badges']
        );

        $columns = [
            [
                'label' => __('Game Date'),
                'key' => 'game_date',
                'is_sortable' => true,
                'render' => function ($game) {
                    return $game->game_date->format('Y-m-d');
                },
            ],
            [
                'label' => __('Root Word'),
                'key' => 'root_word',
                'is_sortable' => true,
                'render' => function ($game) {
                    return '<span class="text-secondary uppercase">'.$game->root_word.'</span>';
                },
            ],
            [
                'label' => __('Center Letter'),
                'key' => 'center_letter',
                'render' => function ($game) {
                    return '<span class="font-bold text-lg text-primary">'.strtoupper($game->center_letter).'</span>';
                },
            ],
            [
                'label' => __('Secret Words'),
                'render' => function ($game) {
                    $wordCount = is_array($game->secret_words) ? count($game->secret_words) : 0;

                    return '<span class="badge badge-primary">'.$wordCount.' words</span>';
                },
            ],
            [
                'label' => __('Total Levels'),
                'key' => 'total_levels',
                'render' => function ($game) {
                    return '<span class="font-medium">'.$game->total_levels.' levels</span>';
                },
            ],
            [
                'label' => __('Total Points'),
                'key' => 'total_points',
                'render' => function ($game) {
                    return '<span class="font-medium text-green-600">'.$game->total_points.' pts</span>';
                },
            ],

            [
                'label' => __('Badges'),
                'render' => function ($game) {
                    $badgeCount = $game->badges->count();

                    return $badgeCount > 0
                        ? '<span class="badge badge-success">'.$badgeCount.' badges</span>'
                        : '<span class="badge badge-secondary">No badges</span>';
                },
            ],
            [
                'label' => __('Active Players'),
                'render' => function ($game) {
                    return $game->players->count();
                },
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'render' => function ($game) {
                    $statusColor = match ($game->status) {
                        GameEnum::ACTIVE => 'success',
                        GameEnum::INACTIVE => 'danger',
                        default => 'secondary'
                    };

                    return '<span class="status '.$statusColor.'">'.__($game->status->value).'</span>';
                },
            ],
            [
                'label' => __('Action'),
                'render' => function ($game) {
                    $action_buttons = [
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'link',
                            'href' => route('admin.games.hexling.edit', $game->id),
                        ],
                        [
                            'label' => __('Change Status'),
                            'icon' => $game->status == GameEnum::ACTIVE ? 'ph ph-toggle-right' : 'ph ph-toggle-left',
                            'type' => 'link',
                            'href' => route('admin.games.hexling.change-status', $game->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.games.hexling.destroy', $game->id),
                        ],
                    ];

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

        $customSearchField = [
            [
                'label' => __('Game Date Range'),
                'type' => 'daterange',
                'name' => ['custom_start_date', 'custom_end_date'],
            ],
        ];

        return view('admin.pages.game.hexling.index', compact('buttons', 'hexlingGames', 'columns', 'customSearchField', 'tab_buttons'));
    }

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

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

        $badges = HexlingBadge::orderBy('badge_order')->get();

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

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

        $request->validate([
            'root_word' => 'required|string|min:3|max:20',
            'center_letter' => 'required|string|size:1',
            'secret_words' => 'required|string',
            'game_date' => 'required|date',
            'status' => 'required|in:active,inactive',
            'badges' => 'required|array|min:1',
            'badges.*' => 'exists:hexling_badges,id',
        ]);

        try {
            DB::beginTransaction();

            // Generate numeric game_id (timestamp-based)
            $gameId = (int) now()->format('YmdHis');

            // Convert secret words from string to array
            $secretWords = array_map('trim', explode(',', $request->secret_words));

            // Calculate total levels (number of badges) and total points (sum of badge points)
            $selectedBadges = HexlingBadge::whereIn('id', $request->badges)->get();
            $totalLevels = $selectedBadges->count();
            $totalPoints = $selectedBadges->sum('badge_points');

            $hexlingWord = HexlingWord::create([
                'game_id' => $gameId,
                'root_word' => $request->root_word,
                'center_letter' => strtolower($request->center_letter),
                'secret_words' => $secretWords,
                'total_levels' => $totalLevels,
                'total_points' => $totalPoints,
                'game_date' => $request->game_date,
                'status' => $request->status,
            ]);

            // Attach badges
            $hexlingWord->badges()->sync($request->badges);

            DB::commit();

            return response()->json([
                'message' => __('Hexling game was successfully created'),
                'redirect' => route('admin.games.hexling.index'),
            ]);

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

            return response()->json([
                'message' => __('Error creating hexling game: ').$e->getMessage(),
            ], 500);
        }
    }

    public function changeHexlingGameStatus(HexlingWord $game)
    {
        adminUserHasPermission(permission: 'edit');

        $game->update([
            'status' => $game->status == GameEnum::ACTIVE ? GameEnum::INACTIVE : GameEnum::ACTIVE,
        ]);

        return redirect()->back()->withSuccess(__('Status changed successfully'));
    }

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

        try {
            DB::beginTransaction();

            // Detach badges first
            $hexling->badges()->detach();

            $hexling->delete();

            DB::commit();

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

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

            return response()->json([
                'message' => __('Error deleting hexling game: ').$e->getMessage(),
            ], 500);
        }
    }

    public function edit(HexlingWord $hexling)
    {
        adminUserHasPermission(permission: 'edit');

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

        $badges = HexlingBadge::orderBy('badge_order')->get();
        $selectedBadges = $hexling->badges->pluck('id')->toArray();

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

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

        $request->validate([
            'root_word' => 'required|string|min:3|max:20',
            'center_letter' => 'required|string|size:1',
            'secret_words' => 'required|string',
            'game_date' => 'required|date',
            'status' => 'required|in:active,inactive',
            'badges' => 'required|array|min:1',
            'badges.*' => 'exists:hexling_badges,id',
        ]);

        try {
            DB::beginTransaction();

            // Convert secret words from string to array
            $secretWords = array_map('trim', explode(',', $request->secret_words));

            // Calculate total levels (number of badges) and total points (sum of badge points)
            $selectedBadges = HexlingBadge::whereIn('id', $request->badges)->get();
            $totalLevels = $selectedBadges->count();
            $totalPoints = $selectedBadges->sum('badge_points');

            $hexling->update([
                'root_word' => $request->root_word,
                'center_letter' => strtolower($request->center_letter),
                'secret_words' => $secretWords,
                'total_levels' => $totalLevels,
                'total_points' => $totalPoints,
                'game_date' => $request->game_date,
                'status' => $request->status,
            ]);

            // Sync badges
            $hexling->badges()->sync($request->badges);

            DB::commit();

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

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

            return response()->json([
                'message' => __('Error updating hexling game: ').$e->getMessage(),
            ], 500);
        }
    }

    /**
     * Calculate total points and levels based on selected badges (for AJAX)
     */
    public function calculateBadgeStats(Request $request)
    {
        $badgeIds = $request->input('badges', []);

        if (empty($badgeIds)) {
            return response()->json([
                'total_levels' => 0,
                'total_points' => 0,
            ]);
        }

        $selectedBadges = HexlingBadge::whereIn('id', $badgeIds)->get();

        return response()->json([
            'total_levels' => $selectedBadges->count(),
            'total_points' => $selectedBadges->sum('badge_points'),
        ]);
    }
}
