<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\CreateUserRequest;
use App\Mail\Admin\UserCreatedMail;
use App\Mail\UserLink;
use App\Models\User;
use App\Services\AdminService;
use Exception;
use Faker\Guesser\Name;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class UsersController extends Controller
{

    protected $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }

    // public function store(Request $request)
    // {

    //     try {
    //         $userData = [
    //             'email' => $request->email,
    //             'authority' => $request->authority,
    //             'tenantId' => $request->tenant_id,
    //             'customerId' => $request->customer_id,
    //             'firstName' => $request->first_name,
    //             'lastName' => $request->last_name,
    //             'phone' => $request->phone,
    //             'name' => $request->name,
    //             'description' => $request->description,
    //             'defaultDashboardId' => $request->default_dashboard_id,
    //             'defaultDashboardFullscreen' => $request->default_dashboard_fullscreen,
    //             'homeDashboardId' => $request->home_dashboard_id,
    //             'homeDashboardHideToolbar' => $request->home_dashboard_hide_toolbar,
    //             'userCredentialsEnabled' => $request->user_credentials_enabled,
    //             'failedLoginAttempts' => $request->failed_login_attempts,
    //             'lastLoginTs' => $request->last_login_ts,
    //             'version' => $request->version,
    //         ];

    //         $response = $this->adminService->createUser($userData);

    //         $user = new User();
    //         $user->id = Str::uuid();
    //         $user->created_time = now()->timestamp;
    //         $user->tenant_id = $request->tenant_id;
    //         $user->customer_id = $request->customer_id;
    //         $user->email = $request->email;
    //         $user->authority = $request->authority;
    //         $user->first_name = $request->first_name;
    //         $user->last_name = $request->last_name;
    //         $user->phone = $request->phone;
    //         $user->version = $request->version;
    //         $user->name = $request->name;
    //         $user->description = $request->description;
    //         $user->default_dashboard_id = $request->default_dashboard_id;
    //         $user->default_dashboard_fullscreen = $request->default_dashboard_fullscreen;
    //         $user->home_dashboard_id = $request->home_dashboard_id;
    //         $user->home_dashboard_hide_toolbar = $request->home_dashboard_hide_toolbar;
    //         $user->user_credentials_enabled = $request->user_credentials_enabled;
    //         $user->failed_login_attempts = $request->failed_login_attempts;
    //         $user->last_login_ts = $request->last_login_ts;
    //         $user->save();

    //         $randomToken = Str::random(64);

    //         $activationLink = url("/apia/activate/{$user->id}?token={$randomToken}");

    //         $mail = Mail::to($user->email)->send(new UserCreatedMail($user, $activationLink));


    //         return response()->json([
    //             'message' => __('auth.data_fetched_successfully'),
    //             'user_id' => $user->id,
    //             'activation_link' => $activationLink,
    //             'token' => $randomToken,
    //             'data' => $response
    //         ], 200);
    //     } catch (QueryException $e) {
    //         Log::error('Error in creating User ' . $e->getMessage());
    //         return jsonResponseWithErrorMessageApi(__('auth.something went wrong'), 401);
    //     }
    // }



    // public function store(Request $request)
    // {
    //     try {
    //         // Validation rules
    //         $validator = Validator::make($request->all(), [
    //             'email' => 'required|email|unique:users,email',
    //             'authority' => 'required|string',
    //             'tenant_id' => 'required|uuid',
    //             'customer_id' => 'nullable|uuid',
    //             'first_name' => 'required|string|max:255',
    //             'last_name' => 'required|string|max:255',
    //             'phone' => 'nullable|string|max:20',
    //             'name' => 'required|string|max:255',
    //             'description' => 'nullable|string',
    //             'default_dashboard_id' => 'nullable|uuid',
    //             'home_dashboard_id' => 'nullable|uuid',
    //             'user_credentials_enabled' => 'nullable|boolean',
    //             'failed_login_attempts' => 'nullable|integer',
    //             'version' => 'nullable|integer',

    //         ]);

    //         if ($validator->fails()) {
    //             return response()->json([
    //                 'success' => false,
    //                 'message' => 'Validation failed',
    //                 'errors' => $validator->errors()
    //             ], 422);
    //         }

    //         // Generate UUID for the user
    //         $userId = Str::uuid();
    //         $currentTimestamp = now()->timestamp;

    //         // Create local user FIRST to ensure all fields are set
    //         $user = User::create([
    //             'id' => $userId,
    //             'email' => $request->email,
    //             'authority' => $request->authority,
    //             'tenant_id' => $request->tenant_id,
    //             'customer_id' => $request->customer_id,
    //             'first_name' => $request->first_name,
    //             'last_name' => $request->last_name,
    //             'phone' => $request->phone,
    //             'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
    //             'description' => $request->description,
    //             'created_time' => $currentTimestamp,
    //             'created_at' => now(),
    //             'updated_at' => now()
    //         ]);

    //         // Prepare data for external service
    //         $serviceData = [
    //             'email' => $request->email,
    //             'authority' => $request->authority,
    //             'first_name' => $request->first_name,
    //             'last_name' => $request->last_name,
    //             'phone' => $request->phone,
    //             'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
    //             'description' => $request->description,
    //             'tenant_id' => $request->tenant_id,
    //             'customer_id' => $request->customer_id
    //         ];

    //         // Create user in external service
    //         $serviceResponse = $this->adminService->createUser($serviceData);

    //         if (isset($serviceResponse['error'])) {
    //             // Rollback local creation if service fails
    //             $user->delete();
    //             throw new \Exception($serviceResponse['message']);
    //         }

    //         // Generate activation token and link
    //         $randomToken = Str::random(64);
    //         $activationLink = url("/apia/activate/{$userId}?token={$randomToken}");

    //         // Send activation email
    //         Mail::to($user->email)->queue(new UserCreatedMail($user, $activationLink));

    //         return response()->json([
    //             'success' => true,
    //             'message' => 'User created successfully',
    //             'data' => [
    //                 'user_id' => $userId,
    //                 'activation_link' => $activationLink,
    //                 'external_service_response' => $serviceResponse
    //             ]
    //         ], 201);

    //     } catch (QueryException $e) {
    //         Log::error('Database error creating user: ' . $e->getMessage());
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Database error creating user',
    //             'error' => config('app.debug') ? $e->getMessage() : null
    //         ], 500);

    //     } catch (\Exception $e) {
    //         Log::error('Error creating user: ' . $e->getMessage());
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to create user',
    //             'error' => config('app.debug') ? $e->getMessage() : null
    //         ], 500);
    //     }
    // }

    public function store(Request $request)
    {
        try {

            $userEmailExist = User::where('email', $request->email)->first();
            if ($userEmailExist) {
                // return response()->json(['status' => 'error','message' => 'Email already exists'],400);
                return jsonResponseWithErrorMessage('Email already exists', 400);

            }

            // Generate UUID for the user
            $userId = Str::uuid();
            $currentTimestamp = now()->timestamp;

            // Create user with ALL fields
            $user = User::create([
                'id' => $userId,
                'email' => $request->email,
                'authority' => $request->authority ?? 'CUSTOMER_USER',
                'tenant_id' => $request->tenant_id ?? null,
                'customer_id' => $request->customer_id ?? null,
                'first_name' => $request->first_name ?? '',
                'last_name' => $request->last_name ?? '',
                'phone' => $request->phone ?? null,
                'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
                'description' => $request->description ?? null,
                'default_dashboard_id' => $request->default_dashboard_id ?? null,
                'default_dashboard_fullscreen' => $request->default_dashboard_fullscreen ?? false,
                'home_dashboard_id' => $request->home_dashboard_id ?? null,
                'home_dashboard_hide_toolbar' => $request->home_dashboard_hide_toolbar ?? false,
                'user_credentials_enabled' => 0,
                'failed_login_attempts' => $request->failed_login_attempts ?? 0,
                'last_login_ts' => $request->last_login_ts,
                'version' => $request->version ?? 0,
                'created_time' => $currentTimestamp,
                'created_at' => now(),
                'updated_at' => now()
            ]);

            $serviceData = [
                'email' => $request->email,
                'authority' => $request->authority ?? null,
                'firstName' => $request->first_name,
                'lastName' => $request->last_name,
                'phone' => $request->phone,
                'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
                'description' => $request->description,
                'tenant_id' => 'bbab7c17-2f19-4eff-9ce7-63870e02b522',
                'customer_id' => $request->customer_id
            ];

            if ($request->filled('customer_id')) {
                $serviceData['customerId'] = [
                    'id' => $request->customer_id,
                    'entityType' => 'CUSTOMER'
                ];
            }
            $serviceResponse = $this->adminService->createUser($serviceData);


            // if (isset($serviceResponse['error'])) {
            //     $user->delete();
            //     throw new \Exception($serviceResponse['message']);
            // }

            $randomToken = Str::random(64);

            // $activationLink = url("/apia/activate/{$userId}?token={$randomToken}");
            $newActivationLink = env('FRONTEND_URL') . "generate-password/{$userId}/{$randomToken}";
            // Send activation email

            $mail = Mail::to($user->email)->send(new UserCreatedMail($user, $newActivationLink));

            return response()->json([
                'status_code' => 200,
                'success' => true,
                'message' => 'User created successfully',
                'data' => [
                    'user_id' => $userId,
                    'token' => $randomToken,
                    'activation_link' => $newActivationLink,
                    // 'external_service_response' => $serviceResponse
                ]
            ], 201);
        } catch (QueryException $e) {
            Log::error('Database error creating user: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Database error creating user',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        } catch (\Exception $e) {
            Log::error('Error creating user: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to create user',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    public function list()
    {
        try {
            $users = User::orderBy('created_at', 'desc')->get();

            if (!empty($users)) {
                return response()->json([
                    'message' => 'Users fetched successfully',
                    'count' => $users->count(),
                    'users' => $users
                ], 200);
            }

            return response()->json(['message' => 'No users found'], 404);
        } catch (Exception $e) {
            return response()->json(['error' => 'Failed to fetch users', 'details' => $e->getMessage()], 500);
        }
    }
    public function delete(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required|string|uuid'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'error' => $validator->errors()->first()
                ], 400);
            }

            $userId = $request->input('user_id');
            $errors = [];
            $success = true;

            // First try to delete from ThingsBoard
            $tbResponse = $this->adminService->deleteUser($userId);


            $user = User::find($userId);

            if ($user) {
                try {
                    $user->delete();
                } catch (\Exception $e) {
                    $errors['local'] = 'Failed to delete from local database';
                    $success = false;
                    Log::error("Local user deletion failed: " . $e->getMessage());
                }
            } else {
                $errors['local'] = "User not found in local database";
                $success = false;
            }

            if (!$success) {
                return response()->json([
                    'success' => false,
                    'message' => 'Partial or complete deletion failed',
                    'errors' => $errors,
                    'details' => $tbResponse['details'] ?? null
                ], count($errors) === 2 ? 500 : 404);
            }

            return response()->json([
                'success' => true,
                'message' => 'User deleted successfully from both systems',
                'thingsboard_response' => $tbResponse['data'] ?? null
            ], 200);
        } catch (\Exception $e) {
            Log::error('User deletion failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'error' => 'Failed to complete deletion process',
                'details' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }




    // public function activate(Request $request, $id)
    // {
    //     Log::info('Full Request URL: ' . $request->fullUrl());

    //     try {
    //         $user = User::find($id);

    //         if (!$user) {
    //             Log::error("User not found for ID: {$id}");
    //             return response()->json([
    //                 'status' => false,
    //                 'message' => 'User not found.'
    //             ], 404);
    //         }

    //         $token = $request->query('token');
    //         if (!$token) {
    //             Log::error("Token missing for User ID: {$id}");
    //             return response()->json([
    //                 'status' => false,
    //                 'message' => 'Invalid activation link.'
    //             ], 401);
    //         }

    //         // Update password in Laravel
    //         $user->password = Hash::make('password');
    //         $user->save();
    //         Log::info("Password updated for User ID: {$id} in Laravel.");

    //         // Activate user in ThingsBoard
    //         $activateToken = $token;
    //         $password = 'password';

    //         try {
    //             $this->adminService->activateUser($user, $password, $activateToken);
    //             Log::info("User ID: {$id} activated successfully in ThingsBoard.");

    //             return response()->json([
    //                 'status' => true,
    //                 'message' => 'User activated and password updated successfully!',
    //                 'user_id' => $user->id
    //             ], 200);

    //         } catch (\Exception $e) {
    //             Log::error("ThingsBoard activation failed: " . $e->getMessage());

    //             // If token is invalid or user is already activated, skip activation
    //             if (str_contains($e->getMessage(), 'Unable to find user credentials')) {
    //                 return response()->json([
    //                     'status' => true,
    //                     'message' => 'User is already activated. Password updated successfully.'
    //                 ], 200);
    //             }

    //             return response()->json([
    //                 'status' => false,
    //                 'message' => 'Failed to activate user in ThingsBoard.',
    //                 'error' => $e->getMessage()
    //             ], 500);
    //         }

    //     } catch (\Exception $e) {
    //         Log::error("Error activating user ID: {$id}. Exception: " . $e->getMessage());
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'An error occurred. Please try again later.',
    //             'error' => $e->getMessage()
    //         ], 500);
    //     }
    // }


    public function activate($id, $token, Request $request)
    {

        try {
            $user = User::find($id);

            if (!$user) {
                Log::error("User not found for ID: {$id}");
                return response()->json([
                    'status' => false,
                    'message' => 'User not found.'
                ], 404);
            }

            if (!$token) {
                Log::error("Token missing for User ID: {$id}");
                return response()->json([
                    'status' => false,
                    'message' => 'Invalid activation link.'
                ], 401);
            }

            // Update password in Laravel
            $user->password = Hash::make($request->password);
            $user->user_credentials_enabled = 1;
            $user->save();
            Log::info("Password updated for User ID: {$id} in Laravel.");

            // Dummy email for ThingsBoardg
            // $dummyEmail = 'dummy+' . $user->id . '@example.com';

            try {
                $this->adminService->activateUser($user, 'password', $token);
                Log::info("User ID: {$id} activated successfully in ThingsBoard.");

                return response()->json([
                    'status' => true,
                    'message' => 'User activated and password updated successfully!',
                    'user_id' => $user->id,
                    'real_email' => $user->email,
                    // 'tb_email' => $dummyEmail
                ], 200);
            } catch (\Exception $e) {
                Log::error("ThingsBoard activation failed: " . $e->getMessage());

                if (str_contains($e->getMessage(), 'Unable to find user credentials')) {
                    return response()->json([
                        'status' => true,
                        'message' => 'User is already activated. Password updated successfully.',
                        'user_id' => $user->id,
                        'real_email' => $user->email,
                        // 'tb_email' => $dummyEmail
                    ], 200);
                }

                return response()->json([
                    'status' => false,
                    'message' => 'Failed to activate user in ThingsBoard.',
                    'error' => $e->getMessage()
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error("Error activating user ID: {$id}. Exception: " . $e->getMessage());
            return response()->json([
                'status' => false,
                'message' => 'An error occurred. Please try again later.',
                'error' => $e->getMessage()
            ], 500);
        }
    }





    // public function autoLogin(Request $request)
    // {
    //     $request->validate([
    //         'email' => 'required|email'
    //     ]);

    //     $email = $request->email;

    //     $user = User::where('email', $email)->first();

    //     if (!$user) {
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'User not found in Laravel. Please register or verify your email.'
    //         ], 404);
    //     }

    //     Auth::login($user);

    //     $thingsboardUser = $this->adminService->getUserByEmail($email);

    //     if ($thingsboardUser) {
    //         $tbUserId = $thingsboardUser['id']['id'];
    //         $thingsboardDashboardUrl = "http://your-thingsboard-domain.com/dashboard/{$tbUserId}";
    //     } else {
    //         $thingsboardDashboardUrl = null;
    //     }

    //     return response()->json([
    //         'status' => true,
    //         'message' => 'User found, redirecting to dashboards...',
    //         'laravel_dashboard_url' => url("/dashboard/{$user->id}"),
    //         'thingsboard_dashboard_url' => $thingsboardDashboardUrl
    //     ], 200);
    // }


    // public function loginUser(Request $request)
    // {
    //     $email = $request->input('email');

    //     if (!$email) {
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'Email is required.'
    //         ], 400);
    //     }

    //     $localResponse = null;
    //     $thingsboardResponse = null;

    //     // ✅ Check in local database
    //     $user = User::where('email', $email)->first();

    //     if ($user) {
    //         $localResponse = [
    //             'status' => true,
    //             'message' => 'Login successful (Local). Redirecting to Local dashboard...',
    //             'user_id' => $user->id,
    //             'email' => $email,
    //             'dashboard_url' => url('/dashboard')  // Local dashboard URL
    //         ];
    //     } else {
    //         $localResponse = [
    //             'status' => false,
    //             'message' => 'User not found in Local database.'
    //         ];
    //     }

    //     // ✅ Check in ThingsBoard
    //     $thingsboardResponse = $this->adminService->getUserByIdThingsBoard($email);

    //     if ($thingsboardResponse['status']) {
    //         $thingsboardUser = $thingsboardResponse['user'];
    //         $thingsboardResponse = [
    //             'status' => true,
    //             'message' => 'Login successful (ThingsBoard). Redirecting to ThingsBoard dashboard...',
    //             'user_id' => $thingsboardUser['id']['id'],
    //             'email' => $email,
    //             'dashboard_url' => $thingsboardResponse['dashboard_url']
    //         ];
    //     } else {
    //         $thingsboardResponse = [
    //             'status' => false,
    //             'message' => 'User not found in ThingsBoard.'
    //         ];
    //     }

    //     // ✅ Return both responses
    //     return response()->json([
    //         'local' => $localResponse,
    //         'thingsboard' => $thingsboardResponse
    //     ], 200);
    // }

    public function loginUser(Request $request)
    {
        $email = $request->input('email');

        if (!$email) {
            return response()->json([
                'status' => false,
                'message' => 'Email is required.'
            ], 400);
        }

        $localResponse = null;
        $thingsboardResponse = null;

        $user = User::where('email', $email)->first();

        if ($user) {
            $token = JWTAuth::fromUser($user);

            $localResponse = [
                'type' => 1,
                'status' => true,
                'message' => 'Login successful (Local). Redirecting to Local dashboard...',
                'data' => [
                    'access_token' => $token,
                    'user' => $user,
                ],
            ];
        } else {
            $localResponse = [
                'status' => false,
                'message' => 'User not found in Local database.'
            ];
        }

        // $thingsboardResponse = $this->adminService->getUserByEmailThingsBoard($email);

        // ✅ Return both responses
        return response()->json($localResponse);
    }




    public function userlistCustomer(Request $request)
    {
        try {
            // Validate the request input
            $validator = Validator::make($request->all(), [
                'customer_id' => 'required|string' // or 'uuid'/'integer' depending on your ID format
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'error' => $validator->errors()->first()
                ], 400);
            }

            $customerId = $request->input('customer_id');
            $users = User::where('customer_id', $customerId)->get();

            if ($users->isEmpty()) {
                return response()->json([
                    'message' => 'No users found for this customer ID'
                ], 404);
            }

            return response()->json([
                'message' => 'Users fetched successfully',
                'users' => $users
            ], 200);
        } catch (\Exception $e) {
            Log::error("Customer user listing error: " . $e->getMessage());
            return response()->json([
                'error' => 'Failed to fetch users',
                'details' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    public function UserByCustomerId($customerId)
    {
        try {
            $users = User::with('customer:id,name')
                ->where('customer_id', $customerId)
                ->get()
                ->map(function ($user) {
                    $userArray = $user->toArray();

                    unset($userArray['customer']);

                    $userArray['customer_name'] = optional($user->customer)->name;

                    return $userArray;
                });

            if ($users->isEmpty()) {
                return response()->json(['message' => 'No users found for this customer ID'], 200);
            }

            return jsonResponseWithSuccessMessage('Users fetched successfully', [
                'users' => $users
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred in fetching users by customer ID: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }

    public function userEmailCheck(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $email = $request->input('email');
            $user = User::where('email', $email)->first();

            if ($user) {

                // If user
                $mailData = [
                    'name' => $user->first_name,
                    'user_id' => $user->id,
                ];

                Mail::to($user->email)->send(new UserLink($mailData));

                return response()->json([
                    'success' => true,
                    'message' => 'Email exists',
                    'user_id' => $user->id
                ], 200);
            }

            return response()->json([
                'success' => false,
                'message' => 'Email does not exist'
            ], 404);
        } catch (Exception $e) {
            Log::error("An error occurred while checking email: " . $e->getMessage());
            return response()->json(['error' => 'Failed to check email', 'details' => $e->getMessage()], 500);
        }
    }

    public function userUpdatePassword(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'password' => 'required'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $userId = $request->input('user_id');
            $password = $request->input('password');

            $user = User::find($userId);

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

            // Update password
            $user->password = Hash::make($password);
            $user->save();

            return response()->json([
                'success' => true,
                'message' => 'Password updated successfully'
            ], 200);
        } catch (Exception $e) {
            Log::error("An error occurred while updating password: " . $e->getMessage());
            return response()->json(['error' => 'Failed to update password', 'details' => $e->getMessage()], 500);
        }
    }
}
