<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Models\PwFactionBonus;
use App\Services\Api\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;

class FactionController extends Controller
{
    protected API $api;

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

    private function transformLevel(int $level): int
    {
        if ($level === 2) {
            return 3;
        }
        if ($level === 0) {
            return 1;
        }

        return $level;
    }

    public function index(Request $request)
    {
        $factions = [];
        $search = $request->input('search');
        $searchType = $request->input('type', 'id');

        if ($search) {
            if ($searchType === 'id' && is_numeric($search)) {
                $factionId = (int) $search;
                $factionInfo = $this->api->getFactionInfo($factionId);

                if ($factionInfo && isset($factionInfo['fid']) && $factionInfo['fid'] > 0) {
                    $members = $factionInfo['member'] ?? [];
                    $factions[] = [
                        'id' => $factionInfo['fid'],
                        'name' => $factionInfo['name'] ?? 'Unknown',
                        'level' => $this->transformLevel($factionInfo['level'] ?? 0),
                        'member_count' => is_array($members) ? count($members) : 0,
                    ];
                }
            }
        }

        return Inertia::render('admin/manage/factions/index', [
            'factions' => $factions,
            'filters' => $request->only(['search', 'type']),
        ]);
    }

    public function getAllFactions(Request $request): JsonResponse
    {
        $page = (int) $request->input('page', 1);
        $perPage = 50;
        $startId = (($page - 1) * $perPage) + 1;
        $endId = $startId + $perPage - 1;

        $factions = [];
        $foundCount = 0;

        // Scan faction IDs in range
        for ($factionId = $startId; $factionId <= $endId + 100; $factionId++) {
            try {
                $factionInfo = $this->api->getFactionInfo($factionId);

                if ($factionInfo && isset($factionInfo['fid']) && $factionInfo['fid'] > 0) {
                    $members = $factionInfo['member'] ?? [];
                    $factions[] = [
                        'id' => $factionInfo['fid'],
                        'name' => $factionInfo['name'] ?? 'Unknown',
                        'level' => $this->transformLevel($factionInfo['level'] ?? 0),
                        'member_count' => is_array($members) ? count($members) : 0,
                    ];
                    $foundCount++;

                    if ($foundCount >= $perPage) {
                        break;
                    }
                }
            } catch (\Exception $e) {
                continue;
            }
        }

        return response()->json([
            'factions' => $factions,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $perPage,
                'has_more' => $foundCount >= $perPage,
            ],
        ]);
    }

    public function show(int $factionId)
    {
        $factionInfo = $this->api->getFactionInfo($factionId);

        if (! $factionInfo || ! isset($factionInfo['fid']) || $factionInfo['fid'] == 0) {
            return redirect()->route('admin.manage-factions')->with('error', 'Faction not found');
        }

        // Get online players list for status check
        $onlineList = [];
        try {
            $onlineList = $this->api->getOnlineList();
        } catch (\Exception $e) {
            // Continue without online status if API fails
        }
        $onlineRoleIds = array_column($onlineList, 'roleid');

        $members = $factionInfo['member'] ?? [];
        $memberList = [];

        if (is_array($members)) {
            foreach ($members as $member) {
                $roleId = $member['roleid'] ?? 0;
                $memberInfo = $this->api->getUserFaction($roleId);

                $memberList[] = [
                    'roleid' => $memberInfo['rid'] ?? $roleId,
                    'name' => $memberInfo['name'] ?? 'Unknown',
                    'role' => $member['role'] ?? 0,
                    'cls' => $memberInfo['cls'] ?? 0,
                    'nickname' => $memberInfo['nickname'] ?? '',
                    'is_online' => in_array($roleId, $onlineRoleIds),
                ];
            }
        }

        return Inertia::render('admin/manage/factions/show', [
            'faction' => [
                'id' => $factionInfo['fid'],
                'name' => $factionInfo['name'] ?? 'Unknown',
                'level' => $this->transformLevel($factionInfo['level'] ?? 0),
                'member_count' => count($memberList),
            ],
            'members' => $memberList,
        ]);
    }

    public function getBonus(int $factionId): JsonResponse
    {
        $bonus = PwFactionBonus::where('faction_id', $factionId)->first();

        return response()->json([
            'bonus' => $bonus ? [
                'faction_id' => $bonus->faction_id,
                'faction_name' => $bonus->faction_name,
                'bonus_percentage' => (float) $bonus->bonus_percentage,
            ] : null,
        ]);
    }

    public function setBonus(Request $request, int $factionId): JsonResponse
    {
        $validated = $request->validate([
            'faction_name' => 'required|string|max:255',
            'bonus_percentage' => 'required|numeric|min:0|max:100',
        ]);

        $bonus = PwFactionBonus::updateOrCreate(
            ['faction_id' => $factionId],
            [
                'faction_name' => $validated['faction_name'],
                'bonus_percentage' => $validated['bonus_percentage'],
            ]
        );

        return response()->json([
            'message' => 'Faction bonus updated successfully',
            'bonus' => [
                'faction_id' => $bonus->faction_id,
                'faction_name' => $bonus->faction_name,
                'bonus_percentage' => (float) $bonus->bonus_percentage,
            ],
        ]);
    }
}
