<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\ActivityLogger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::orderBy('created_at', 'desc')->paginate(10);

        return view('admin.users.index', compact('users'));
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        return view('admin.users.show', compact('user'));
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'avatar' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'bio' => 'nullable|string|max:1000',
            'task' => 'nullable|string|max:255',
            'is_admin' => 'boolean',
            'is_banned' => 'boolean',
        ]);

        $data = $request->except(['avatar', 'is_admin', 'is_banned']);

        if (Schema::hasColumn('users', 'avatar') && $request->hasFile('avatar')) {
            if ($user->avatar) {
                Storage::disk('public')->delete($user->avatar);
            }

            $data['avatar'] = $request->file('avatar')->store('avatars', 'public');
        }

        foreach (['task', 'bio'] as $column) {
            if (! Schema::hasColumn('users', $column)) {
                unset($data[$column]);
            }
        }

        if (! Schema::hasColumn('users', 'avatar')) {
            unset($data['avatar']);
        }

        if ($user->id !== auth()->id()) {
            $data['is_admin'] = $request->boolean('is_admin');
            $data['is_banned'] = $request->boolean('is_banned');
        }

        $before = [
            'is_admin' => $user->is_admin,
            'is_banned' => $user->is_banned,
            'email' => $user->email,
        ];

        $user->update($data);

        ActivityLogger::log(
            'user.updated',
            $user->name,
            $user,
            ['before' => $before, 'after' => ['is_admin' => $user->is_admin, 'is_banned' => $user->is_banned, 'email' => $user->email]]
        );

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user)
    {
        if ($user->id === auth()->id()) {
            return redirect()->route('admin.users.index')
                ->with('error', __('You cannot delete yourself!'));
        }

        ActivityLogger::log('user.deleted', $user->email, $user, ['name' => $user->name]);

        $user->delete();

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

    /**
     * Toggle admin status for the specified user.
     */
    public function toggleAdmin(User $user)
    {
        if ($user->id === auth()->id()) {
            return redirect()->route('admin.users.index')
                ->with('error', __('You cannot change your own admin status!'));
        }

        $user->update(['is_admin' => ! $user->is_admin]);

        ActivityLogger::log(
            $user->is_admin ? 'user.promoted_admin' : 'user.demoted_admin',
            $user->name,
            $user,
            ['is_admin' => $user->is_admin]
        );

        return redirect()->route('admin.users.index')
            ->with('success', $user->is_admin
                ? __('User promoted to admin')
                : __('User demoted from admin'));
    }

    /**
     * Toggle ban status for the specified user.
     */
    public function toggleBan(User $user)
    {
        if ($user->id === auth()->id()) {
            return redirect()->route('admin.users.index')
                ->with('error', __('You cannot ban yourself!'));
        }

        $user->update(['is_banned' => ! $user->is_banned]);

        ActivityLogger::log(
            $user->is_banned ? 'user.banned' : 'user.unbanned',
            $user->name,
            $user,
            ['is_banned' => $user->is_banned]
        );

        return redirect()->route('admin.users.index')
            ->with('success', $user->is_banned
                ? __('User banned successfully!')
                : __('User unbanned successfully!'));
    }

    /**
     * Display the team list.
     */
    public function team()
    {
        $users = User::query()
            ->where('is_admin', true)
            ->where('is_banned', false)
            ->orderBy('created_at', 'desc')
            ->get();

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