<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\User;
use Carbon\Carbon;

class LoginController extends Controller
{
    /**
     * Handle user login request.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        // Rate limiting
        $this->checkRateLimit($request);

        // Validate the request
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email'],
            'password' => ['required', 'string', 'min:6'],
        ]);

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

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

        // Check if user exists and password is correct
        if (!$user || !Hash::check($request->password, $user->password)) {
            $this->incrementRateLimit($request);
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials'
            ], 401);
        }

        // Check if user account is active
        if (!$user->is_active) {
            return response()->json([
                'success' => false,
                'message' => 'Your account has been deactivated. Please contact support.'
            ], 403);
        }

        // Update last login timestamp
        $user->update(['last_login_at' => Carbon::now()]);

        // Create authentication token
        $token = $user->createToken('auth-token')->plainTextToken;

        // Also log the user into Laravel session for dashboard access
        Auth::login($user, $request->boolean('remember'));

        // Clear rate limiting
        RateLimiter::clear($this->throttleKey($request));

        return response()->json([
            'success' => true,
            'message' => 'Login successful',
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'phone' => $user->phone,
                'last_login_at' => $user->last_login_at
            ],
            'token' => $token
        ]);
    }

    /**
     * Handle user registration request.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        // Rate limiting for registration
        $this->checkRateLimit($request, 'register');

        // Validate the request
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

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

        try {
            // Create the user
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'patient', // Default role
                'is_active' => true,
            ]);

            // Log the user in
            Auth::login($user);

            // Update last login time
            $user->last_login_at = now();
            $user->save();

            // Generate API token
            $token = $user->createToken('auth_token')->plainTextToken;

            // Clear rate limit on successful registration
            $this->clearRateLimit($request, 'register');

            return response()->json([
                'success' => true,
                'message' => 'Registration successful',
                'user' => $user,
                'token' => $token
            ]);

        } catch (\Exception $e) {
            $this->incrementRateLimit($request, 'register');
            return response()->json([
                'success' => false,
                'message' => 'Registration failed. Please try again.',
            ], 500);
        }
    }

    /**
     * Handle user logout request.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        // Delete current access token
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully'
        ]);
    }

    /**
     * Get the authenticated user.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function user(Request $request)
    {
        $user = $request->user();
        
        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'phone' => $user->phone,
                'last_login_at' => $user->last_login_at
            ]
        ]);
    }

    /**
     * Check rate limiting for login attempts.
     *
     * @param \Illuminate\Http\Request $request
     * @return void
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function checkRateLimit(Request $request, $prefix = 'login')
    {
        $key = $this->throttleKey($request, $prefix);
        $maxAttempts = 5; // Maximum 5 attempts
        $decayMinutes = 15; // Lock for 15 minutes

        if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
            $seconds = RateLimiter::availableIn($key);
            $action = $prefix === 'register' ? 'registration' : 'login';
            throw ValidationException::withMessages([
                'email' => ["Too many {$action} attempts. Please try again in {$seconds} seconds."]
            ]);
        }
    }

    /**
     * Increment rate limit attempts.
     *
     * @param \Illuminate\Http\Request $request
     * @return void
     */
    protected function incrementRateLimit(Request $request, $prefix = 'login')
    {
        RateLimiter::hit($this->throttleKey($request, $prefix), 900); // 15 minutes
    }

    /**
     * Clear rate limit attempts.
     *
     * @param \Illuminate\Http\Request $request
     * @param string $prefix
     * @return void
     */
    protected function clearRateLimit(Request $request, $prefix = 'login')
    {
        RateLimiter::clear($this->throttleKey($request, $prefix));
    }

    /**
     * Handle traditional web form login (for session-based authentication).
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function webLogin(Request $request)
    {
        // Rate limiting
        $this->checkRateLimit($request);

        // Validate the request
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email'],
            'password' => ['required', 'string', 'min:6'],
        ]);

        if ($validator->fails()) {
            $this->incrementRateLimit($request);
            return redirect()->back()
                ->withErrors($validator)
                ->withInput($request->except('password'));
        }

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

        // Check if user exists and password is correct
        if (!$user || !Hash::check($request->password, $user->password)) {
            $this->incrementRateLimit($request);
            return redirect()->back()
                ->withErrors(['email' => 'Invalid credentials'])
                ->withInput($request->except('password'));
        }

        // Check if user account is active
        if (!$user->is_active) {
            return redirect()->back()
                ->withErrors(['email' => 'Your account has been deactivated. Please contact support.'])
                ->withInput($request->except('password'));
        }

        // Update last login timestamp
        $user->update(['last_login_at' => Carbon::now()]);

        // Log the user into Laravel session
        Auth::login($user, $request->boolean('remember'));

        // Clear rate limiting
        RateLimiter::clear($this->throttleKey($request));

        // Redirect to role-based dashboard
        $dashboardRoutes = [
            'doctor' => '/doctor-dashboard',
            'patient' => '/patient-dashboard', 
            'hospital_admin' => '/admin-dashboard',
            'nurse' => '/nurse-dashboard',
            'receptionist' => '/doctor-dashboard'
        ];

        return redirect()->intended($dashboardRoutes[$user->role] ?? '/dashboard');
    }

    /**
     * Get the rate limiting throttle key for the given request.
     *
     * @param \Illuminate\Http\Request $request
     * @return string
     */
    protected function throttleKey(Request $request, $prefix = 'login')
    {
        return $prefix.':'.strtolower($request->input('email')).'|'.$request->ip();
    }
}