<?php

namespace Modules\User\Http\Controllers;

use App\Http\Controllers\BaseCrudController;
use App\Services\ActivityLogger;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Auth\Entities\User;
use Modules\User\Http\Requests\UserRequest;
use Modules\User\Repositories\Contracts\UserRepositoryInterface;
use Modules\User\Services\UserService;
use Modules\Auth\Transformers\UserResource;
use Modules\User\Transformers\UserListResource;

class UserController extends BaseCrudController
{
    protected $modelClass = User::class;

    protected $resourceClass = UserResource::class;

    protected $requestClass = UserRequest::class;

    protected $resourceName = 'user';

    protected $resourceNamePlural = 'users';

    public function __construct(
        UserRepositoryInterface $repository,
        protected UserService $userService
    ) {
        parent::__construct($repository);
    }

    /**
     * Prepare data for store method
     */
    protected function prepareStoreData(array $validated): array
    {
        $validated['uuid'] = Str::uuid();
        $validated['password'] = Hash::make('suteraselamanya');

        return $validated;
    }

    /**
     * Prepare data for update method
     */
    protected function prepareUpdateData(array $validated, $user): array
    {
        unset($validated['uuid']);

        if (! array_key_exists('email', $validated)) {
            unset($validated['email']);
        }

        return $validated;
    }

    /**
     * Check dependencies before deletion
     */
    protected function checkDependencies($user): ?JsonResponse
    {
        return null;
    }

    public function assignRoles(Request $request, $id): JsonResponse
    {
        $request->validate([
            'roles' => 'required|array',
            'roles.*' => 'exists:roles,id,guard_name,api',
        ]);

        $result = $this->userService->assignRoles($id, $request->roles);

        if (isset($result['error'])) {
            $status = $result['error'] === 'User not found.' ? 404 : 400;

            return response()->json([
                'success' => false,
                'message' => $result['error'],
            ], $status);
        }

        return response()->json([
            'success' => true,
            'message' => 'Roles assigned successfully.',
            'data' => (new UserResource($result['user']))->resolve(),
        ]);
    }

    public function updateProfile(Request $request): JsonResponse
    {
        $user = $request->user();

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'ic_number' => 'sometimes|string|max:255|unique:users,ic_number,'.$user->id,
            'position' => 'sometimes|string|max:255',
            'phone_number' => 'sometimes|string|max:255',
            'image' => 'sometimes|image|mimes:jpeg,png,jpg,gif|max:2048',
            'image_url' => 'sometimes|string|max:255',
            'gender' => 'sometimes|string|max:255',
            'marriage_status' => 'sometimes|string|max:255',
            'member_number' => 'sometimes|integer',
            'member_type' => 'sometimes|string|max:255',
            'join_date' => 'sometimes|date',
            'birth_date' => 'sometimes|date',
            'birth_place' => 'sometimes|string|max:255',
        ]);

        $user = $this->userService->updateProfile(
            $user,
            $validated,
            $request->file('image')
        );

        return response()->json([
            'success' => true,
            'data' => new UserResource($user),
            'message' => 'Profile updated successfully.',
        ]);
    }

    public function updatePassword(Request $request): JsonResponse
    {
        $user = $request->user();

        $validated = $request->validate([
            'current_password' => 'required|string',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $result = $this->userService->updatePassword(
            $user,
            $validated['current_password'],
            $validated['password']
        );

        if (isset($result['error'])) {
            return response()->json([
                'success' => false,
                'message' => $result['error'],
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => 'Password updated successfully.',
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $this->authorize('viewAny', $this->modelClass);

        try {
            $perPage = min((int) $request->get('per_page', 10), 500);
            $items = $this->userService->getPaginatedList(
                $perPage,
                $request->get('search', ''),
                $request->get('status', ''),
                $request->get('sort_by', 'id'),
                $request->get('sort_order', 'asc')
            );

            return response()->json([
                'success' => true,
                'data' => UserListResource::collection($items->items()),
                'pagination' => [
                    'current_page' => $items->currentPage(),
                    'per_page' => $items->perPage(),
                    'total' => $items->total(),
                    'last_page' => $items->lastPage(),
                    'from' => $items->firstItem(),
                    'to' => $items->lastItem(),
                    'has_more_pages' => $items->hasMorePages(),
                ],
                'message' => $this->getSuccessMessage('index'),
            ]);
        } catch (Exception $e) {
            Log::error("Error fetching {$this->resourceNamePlural}: ".$e->getMessage());

            return $this->errorResponse($this->getErrorMessage('index'), 500);
        }
    }

    public function deletedIndex(Request $request): JsonResponse
    {
        $this->authorize('viewAny', $this->modelClass);

        try {
            $perPage = min((int) $request->get('per_page', 10), 500);
            $items = $this->userService->getDeletedPaginatedList(
                $perPage,
                $request->get('search', ''),
                $request->get('status', ''),
                $request->get('sort_by', 'deleted_at'),
                $request->get('sort_order', 'desc')
            );

            return response()->json([
                'success' => true,
                'data' => UserListResource::collection($items->items()),
                'pagination' => [
                    'current_page' => $items->currentPage(),
                    'per_page' => $items->perPage(),
                    'total' => $items->total(),
                    'last_page' => $items->lastPage(),
                    'from' => $items->firstItem(),
                    'to' => $items->lastItem(),
                    'has_more_pages' => $items->hasMorePages(),
                ],
                'message' => 'Deleted users retrieved successfully.',
            ]);
        } catch (Exception $e) {
            Log::error("Error fetching deleted {$this->resourceNamePlural}: ".$e->getMessage());

            return $this->errorResponse('Failed to retrieve deleted users.', 500);
        }
    }

    public function restore(string $id): JsonResponse
    {
        $this->authorize('restore', $this->modelClass);

        try {
            $user = $this->userService->restoreUser($id);

            if (! $user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Deleted user not found.',
                ], 404);
            }

            ActivityLogger::log("Restored {$this->resourceName}: {$user->name}", $user);

            return response()->json([
                'success' => true,
                'message' => 'User restored successfully.',
                'data' => (new UserListResource($user))->resolve(),
            ]);
        } catch (Exception $e) {
            Log::error("Error restoring {$this->resourceName}: ".$e->getMessage());

            return $this->errorResponse('Failed to restore user.', 500);
        }
    }

    public function show($id): JsonResponse
    {
        $this->authorize('view', $this->modelClass);

        try {
            $user = $this->userService->getUserWithRelations($id);

            if (! $user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found.',
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => new UserResource($user),
                'message' => 'User retrieved successfully.',
            ]);
        } catch (Exception $e) {
            Log::error('Error fetching user: '.$e->getMessage());

            return $this->errorResponse('Failed to retrieve user.', 500);
        }
    }
}
