<?php

namespace App\Http\Controllers\Admin\game;

use App\Enums\GameEnum;
use App\Http\Controllers\Controller;
use App\Models\WordlingWord;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;

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

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

        $tab_buttons = [
            [
                'label' => __('All Wordling Games'),
                'link' => route('admin.games.wordling.index'),
            ],
            [
                'label' => __('Wordling Main'),
                'count' => WordlingWord::where('game_type', 'wordling_main')->count(),
                'link' => route('admin.games.wordling.index', ['type' => 'wordling_main']),
            ],
            [
                'label' => __('Wordling Mini'),
                'count' => WordlingWord::where('game_type', 'wordling_min')->count(),
                'link' => route('admin.games.wordling.index', ['type' => 'wordling_min']),
            ],
            [
                'label' => __('Wordling Max'),
                'count' => WordlingWord::where('game_type', 'wordling_max')->count(),
                'link' => route('admin.games.wordling.index', ['type' => 'wordling_max']),
            ],
        ];

        $wordlingGames = ModalIndexQuey::get(model: WordlingWord::query()->when(request('type'), function ($query, $type) {
            if ($type === 'wordling_main') {
                $query->where('game_type', 'wordling_main');
            } elseif ($type === 'wordling_min') {
                $query->where('game_type', 'wordling_min');
            } elseif ($type === 'wordling_max') {
                $query->where('game_type', 'wordling_max');
            }
        })->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: ['wordlingPlays']);

        $columns = [
            [
                'label' => __('Game Date'),
                'key' => 'game_date',
                'is_sortable' => true,
                'render' => function ($game) {
                    return $game->game_date->format('Y-m-d');
                },
            ],
            [
                'label' => __('Game Title'),
                'key' => 'game_type',
                'render' => function ($game) {
                    $titles = [
                        'wordling_min' => 'Wordling Mini',
                        'wordling_main' => 'Wordling Main',
                        'wordling_max' => 'Wordling Max',
                    ];

                    $title = $titles[$game->game_type] ?? ucfirst(str_replace('_', ' ', $game->game_type));

                    return '<span class="font-medium text-gray-900">'.$title.'</span>';
                },
            ],
            [
                'label' => __('Secret Word'),
                'key' => 'secret_word',
                'is_sortable' => true,
                'header_class' => 'lg:w-[200px]',
            ],
            [
                'label' => __('Word Length'),
                'key' => 'secret_word_length',
            ],
            [
                'label' => __('Max Attempts'),
                'key' => 'max_attempts',
            ],
            [
                'label' => __('Active Players'),
                'key' => 'active_players_count',
            ],
            [
                'label' => __('Winners'),
                'key' => 'winners_count',
            ],
            [
                'label' => __('Completion Rate'),
                'render' => function ($game) {
                    return $game->completion_rate.'%';
                },
            ],
            [
                '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.wordling.edit', $game->id),
                        ],
                        [
                            'label' => __('Change Status'),
                            'icon' => $game->status == 'active' ? 'ph ph-toggle-right' : 'ph ph-toggle-left',
                            'type' => 'link',
                            'href' => route('admin.games.wordling.change-status', $game->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.games.wordling.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.wordling.index', compact('buttons', 'wordlingGames', 'columns', 'customSearchField', 'tab_buttons'));
    }

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

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

        $languages = \App\Models\Language::active()->get();

        return view('admin.pages.game.wordling.create', compact('buttons', 'languages'));
    }

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

        $request->validate([
            'game_type' => 'required|in:wordling_min,wordling_main,wordling_max',
            'secret_word' => 'required|string|min:3|max:7',
            'game_date' => 'required|date',
            'max_attempts' => 'required|integer|min:1|max:20',
            'status' => 'required|in:active,inactive',
        ]);

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

        WordlingWord::create([
            'game_id' => $gameId,
            'game_type' => $request->game_type,
            'secret_word' => $request->secret_word,
            'secret_word_length' => strlen($request->secret_word),
            'game_date' => $request->game_date,
            'max_attempts' => $request->max_attempts,
            'status' => $request->status,
        ]);

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

    public function changeWordlingGameStatus(WordlingWord $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(WordlingWord $wordling)
    {
        adminUserHasPermission(permission: 'delete');

        $wordling->delete();

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

    public function edit(WordlingWord $wordling)
    {
        adminUserHasPermission(permission: 'edit');

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

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

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

        $request->validate([
            'game_type' => 'required|in:wordling_min,wordling_main,wordling_max',
            'secret_word' => 'required|string|min:3|max:7',
            'game_date' => 'required|date',
            'max_attempts' => 'required|integer|min:1|max:20',
            'status' => 'required|in:active,inactive',
        ]);

        try {
            $wordling->update([
                'game_type' => $request->game_type,
                'secret_word' => $request->secret_word,
                'secret_word_length' => strlen($request->secret_word),
                'game_date' => $request->game_date,
                'max_attempts' => $request->max_attempts,
                'status' => $request->status,
            ]);

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

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