<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreUserRequest;
use App\Http\Requests\Admin\UpdateUserRequest;
use App\Http\Requests\Admin\UpdateAddCardRequest;
use App\DTOs\UserFilterDto;
use App\Services\Admin\Contracts\AdminServiceInterface;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminController extends Controller
{
    public function __construct(
        private readonly AdminServiceInterface $adminService
    ) {}

    /**
     * Display a listing of the users with statistics.
     */
    public function index(Request $request): View|JsonResponse
    {
        $filters = UserFilterDto::fromRequest($request);

        [
            'users' => $users,
            'topReceivedUser' => $topReceivedUser,
            'topSentUser' => $topSentUser,
            'topReceivedUsers' => $topReceivedUsers,
            'topSentUsers' => $topSentUsers
        ] = $this->adminService->getUserListWithStats($filters);

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'title' => view('admin.users.partials.title', ['selectedMonth' => $filters->selectedMonth])->render(),
                'stats' => view('admin.users.partials.stats', compact('topReceivedUser', 'topSentUser', 'topReceivedUsers', 'topSentUsers'))->render(),
                'table' => view('admin.users.partials.table', compact('users'))->render(),
            ]);
        }

        return view('admin.users.index', compact(
            'users', 
            'topReceivedUser', 
            'topSentUser', 
            'topReceivedUsers',
            'topSentUsers'
        ))->with([
            'selectedMonth' => $filters->selectedMonth,
            'search'        => $filters->search, 
            'status'        => $filters->status,
            'role'          => $filters->role,
            'department'    => $filters->department,
            'flagSend'      => $filters->flagSend,
        ]);
    }

    /**
     * Show the form for creating a new user.
     */
    public function create(): View
    {
        return view('admin.users.form', ['mode' => 'create']);
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(StoreUserRequest $request): RedirectResponse
    {
        $this->adminService->createUser($request->validated());

        return redirect()->route('admin.users.index')->with('success', __('messages.user_create_success'));
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(Request $request, string $msnv): View
    {
        $user            = $this->adminService->getUserByMsnv($msnv);
        $selectedMonth   = (string) $request->input('month', Carbon::now()->format('Y-m'));
        $administrations = $this->adminService->getUserTransactions($msnv, $selectedMonth);
        $addCards        = $this->adminService->getAddCardsHistory($user->msnv, $selectedMonth);
        $admins          = $this->adminService->getActiveAdmins();

        return view('admin.users.form', compact('user', 'administrations', 'selectedMonth', 'addCards', 'admins'))->with('mode', 'edit');
    }

    /**
     * Update the specified user in storage.
     */
    public function update(UpdateUserRequest $request, string $msnv)
    {
        $user = $this->adminService->getUserByMsnv($msnv);
        $validatedData = $request->validated();

        $this->adminService->updateUser($user, $validatedData);

        $currentUser = auth()->user();
        if ($currentUser && $user->id === $currentUser->id && isset($validatedData['status']) && $validatedData['status'] == config('constants.STATUS_INACTIVE')) {
            auth()->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            if ($request->expectsJson() || $request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Tài khoản của bạn đã chuyển sang trạng thái nghỉ việc. Bạn đã được đăng xuất.',
                    'redirect' => route('login'),
                ]);
            }

            return redirect()->route('login')->with('success', 'Tài khoản của bạn đã chuyển sang trạng thái nghỉ việc. Bạn đã được đăng xuất.');
        }

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => __('messages.user_update_success'),
                'card_balance' => $user->fresh()->card,
            ]);
        }

        return redirect()->back()->with('success', __('messages.user_update_success'));
    }

    /**
     * Remove (deactivate) the specified user from storage.
     */
    public function destroy(string $msnv): RedirectResponse
    {
        $user = $this->adminService->getUserByMsnv($msnv);

        $this->adminService->deactivateUser($msnv);

        $currentUser = auth()->user();
        if ($currentUser && $user->id === $currentUser->id) {
            auth()->logout();
            request()->session()->invalidate();
            request()->session()->regenerateToken();

            return redirect()->route('login')->with('success', 'Tài khoản của bạn đã chuyển sang trạng thái nghỉ việc. Bạn đã được đăng xuất.');
        }

        return redirect()->route('admin.users.index')->with('success', __('messages.user_deactivate_success'));
    }

    /**
     * Update card allocation history record.
     */
    public function updateAddCard(UpdateAddCardRequest $request, int $id)
    {
        try {
            $this->adminService->updateAddCard($id, $request->validated());
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Cập nhật lịch sử cấp phát thẻ thành công.',
                ]);
            }
            return redirect()->back()->with('success', 'Cập nhật lịch sử cấp phát thẻ thành công.');
        } catch (\Exception $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage(),
                ], 422);
            }
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Delete card allocation history record.
     */
    public function destroyAddCard(Request $request, int $id)
    {
        try {
            $this->adminService->destroyAddCard($id);
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Xóa lịch sử cấp phát thẻ thành công.',
                ]);
            }
            return redirect()->back()->with('success', 'Xóa lịch sử cấp phát thẻ thành công.');
        } catch (\Exception $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage(),
                ], 422);
            }
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
