<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $search = $request->string('search')->trim()->toString();
        $role = $request->string('role')->trim()->toString();

        $users = User::query()
            ->withCount('trades')
            ->when($search !== '', function ($query) use ($search): void {
                $query->where(function ($query) use ($search): void {
                    $query
                        ->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->when($role !== '', fn ($query) => $query->where('role', $role))
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return view('admin.users.index', [
            'users' => $users,
            'search' => $search,
            'role' => $role,
            'roles' => User::roles(),
            'supportTeamCount' => User::where('role', 'support_team')->count(),
        ]);
    }

    public function supportTeam(): View
    {
        $members = User::where('role', 'support_team')
            ->latest()
            ->paginate(12);

        return view('admin.users.support-team', compact('members'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        abort(404);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        abort(404);
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user): View
    {
        $user->loadCount('trades');

        $trades = $user->trades()
            ->latest('opened_at')
            ->latest()
            ->paginate(10);

        return view('admin.users.show', compact('user', 'trades'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user): View
    {
        return view('admin.users.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, User $user): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', Rule::unique('users')->ignore($user)],
            'role' => ['required', Rule::in(array_keys(User::roles()))],
            'status' => ['required', 'in:active,blocked'],
        ]);

        if ($user->is(auth()->user())) {
            $data['role'] = 'admin';
            $data['status'] = 'active';
        }

        if ($this->wouldRemoveLastAdmin($user, $data['role'], $data['status'])) {
            return back()->with('error', 'You cannot remove or block the last active admin account.');
        }

        $user->update($data);

        return redirect()
            ->route('admin.users.show', $user)
            ->with('success', 'User updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user): RedirectResponse
    {
        if ($user->is(auth()->user())) {
            return back()->with('error', 'You cannot delete your own admin account.');
        }

        if ($this->wouldRemoveLastAdmin($user, 'user', 'blocked')) {
            return back()->with('error', 'You cannot delete the last active admin account.');
        }

        $user->delete();

        return redirect()
            ->route('admin.users.index')
            ->with('success', 'User deleted successfully.');
    }

    public function toggleStatus(User $user): RedirectResponse
    {
        if ($user->is(auth()->user())) {
            return back()->with('error', 'You cannot block your own admin account.');
        }

        $nextStatus = $user->status === 'blocked' ? 'active' : 'blocked';

        if ($this->wouldRemoveLastAdmin($user, $user->role, $nextStatus)) {
            return back()->with('error', 'You cannot block the last active admin account.');
        }

        $user->update([
            'status' => $nextStatus,
        ]);

        return back()->with('success', 'User status updated successfully.');
    }

    public function markEmailVerified(User $user): RedirectResponse
    {
        $user->forceFill([
            'email_verified_at' => $user->email_verified_at ?: now(),
        ])->save();

        return back()->with('success', 'User email marked as verified.');
    }

    private function wouldRemoveLastAdmin(User $user, string $newRole, string $newStatus): bool
    {
        if ($user->role !== 'admin' || $user->status !== 'active') {
            return false;
        }

        if ($newRole === 'admin' && $newStatus === 'active') {
            return false;
        }

        return User::where('role', 'admin')
            ->where('status', 'active')
            ->whereKeyNot($user->id)
            ->doesntExist();
    }
}
