<?php

namespace App\Http\Controllers\Admin\Online;

use App\Http\Controllers\Controller;
use App\Services\Api\API;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class OnlinePlayerController extends Controller
{
    protected API $api;

    protected array $classNames = [
        0 => 'Blademaster',
        1 => 'Mage',
        2 => 'Psychic',
        3 => 'Venomancer',
        4 => 'Barbarian',
        5 => 'Assassin',
        6 => 'Archer',
        7 => 'Cleric',
        8 => 'Seeker',
        9 => 'Mystic',
        10 => 'Duskblade',
        11 => 'Stormbringer',
        12 => 'Technician',
        13 => 'Edgerunner',
        14 => 'Wildwalker',
    ];

    public function __construct(API $api)
    {
        $this->api = $api;
    }

    protected function getFactionName(int $roleId): ?string
    {
        try {
            $userFaction = $this->api->getUserFaction($roleId);
            if (isset($userFaction['fid']) && $userFaction['fid'] > 0) {
                $factionInfo = $this->api->getFactionInfo($userFaction['fid']);
                return $factionInfo['name'] ?? null;
            }
        } catch (\Exception $e) {
            // Ignore errors
        }

        return null;
    }

    protected function buildPlayerData(array $online): array
    {
        $roleId = $online['roleid'] ?? 0;
        if ($roleId <= 0) {
            return [
                'id' => 0,
                'name' => $online['name'] ?? '',
                'user_id' => $online['userid'] ?? 0,
                'class' => 0,
                'class_name' => 'Unknown',
                'level' => 0,
                'level2' => 0,
                'gender' => 0,
                'faction_name' => null,
            ];
        }

        try {
            $base = $this->api->getRoleBase($roleId);
            $status = $this->api->getRoleStatus($roleId);
            $factionName = $this->getFactionName($roleId);

            return [
                'id' => $roleId,
                'name' => $online['name'] ?? (($base ?? [])['name'] ?? ''),
                'user_id' => $online['userid'] ?? (($base ?? [])['userid'] ?? 0),
                'class' => ($base ?? [])['cls'] ?? 0,
                'class_name' => $this->classNames[($base ?? [])['cls'] ?? 0] ?? 'Unknown',
                'level' => ($status ?? [])['level'] ?? 0,
                'level2' => ($status ?? [])['level2'] ?? 0,
                'gender' => ($base ?? [])['gender'] ?? 0,
                'faction_name' => $factionName,
            ];
        } catch (\Exception $e) {
            return [
                'id' => $roleId,
                'name' => $online['name'] ?? '',
                'user_id' => $online['userid'] ?? 0,
                'class' => 0,
                'class_name' => 'Unknown',
                'level' => 0,
                'level2' => 0,
                'gender' => 0,
                'faction_name' => null,
            ];
        }
    }

    public function index(Request $request): Response
    {
        $searchQuery = $request->input('search', '');
        $loadAll = $request->has('load');

        if (!$loadAll && empty($searchQuery)) {
            return Inertia::render('admin/online/index', [
                'onlinePlayers' => [],
                'count' => 0,
                'loaded' => false,
                'searchQuery' => '',
            ]);
        }

        $onlineList = $this->api->getOnlineList();

        $onlinePlayers = [];
        foreach ($onlineList as $online) {
            if (!empty($searchQuery)) {
                $playerName = strtolower($online['name'] ?? '');
                if (!str_contains($playerName, strtolower($searchQuery))) {
                    continue;
                }
            }

            $playerData = $this->buildPlayerData($online);
            if ($playerData['id'] > 0) {
                $onlinePlayers[] = $playerData;
            }
        }

        return Inertia::render('admin/online/index', [
            'onlinePlayers' => $onlinePlayers,
            'count' => count($onlinePlayers),
            'loaded' => true,
            'searchQuery' => $searchQuery,
        ]);
    }

    public function loadAll(): Response
    {
        return redirect()->route('admin.online', ['load' => true]);
    }
}
