<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Validation\ValidationException;
use App\Services\ActionNotificationService;
use App\Mail\SignupWelcomeMail;

class AuthController extends \App\Http\Controllers\Controller
{
    /**
     * Build mobile routing hints for onboarding vs dashboard.
     */
    private function buildRoutingState(User $user): array
    {
        $hasCompany = !is_null($user->company_id);
        $onboardingRequired = !$hasCompany && $user->role !== 'admin';

        return [
            'has_company' => $hasCompany,
            'onboarding_required' => $onboardingRequired,
            'next_screen' => $onboardingRequired ? 'onboarding' : 'dashboard',
            'company_id' => $user->company_id,
        ];
    }

    /**
     * Register a new user
     */
    public function register(Request $request, ActionNotificationService $notifications): JsonResponse
    {
        // Debug: log raw input and headers
        \Log::info('Register raw input', [
            'raw' => $request->getContent(),
            'all' => $request->all(),
            'headers' => $request->headers->all(),
        ]);
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|unique:users',
                'password' => 'required|string|min:8|confirmed',
                'role' => 'required|in:owner,driver,admin',
            ]);

            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => Hash::make($validated['password']),
                'role' => $validated['role'],
            ]);

            // Send welcome email to the new user
            Mail::to($user->email)->queue(new SignupWelcomeMail($user, 'mobile'));

            // Send notification email to admins
            $notifications->notifyAction(
                'Mobile Signup',
                $user,
                [
                    'channel' => 'mobile',
                    'role' => $user->role,
                    'email' => $user->email,
                ]
            );

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

            return response()->json([
                'success' => true,
                'message' => 'User registered successfully',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => $user->role,
                ],
                'routing' => $this->buildRoutingState($user),
                'token' => $token,
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors(),
            ], 422);
        }
    }

    /**
     * Login user
     */
    public function login(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'email' => 'required|string|email',
                'password' => 'required|string',
            ]);

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

            if (!$user || !Hash::check($validated['password'], $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid credentials',
                ], 401);
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Login successful',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => $user->role,
                ],
                'routing' => $this->buildRoutingState($user),
                'token' => $token,
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors(),
            ], 422);
        }
    }

    /**
     * Logout user
     */
    public function logout(Request $request): JsonResponse
    {
        JWTAuth::invalidate(JWTAuth::getToken());
        return response()->json([
            'success' => true,
            'message' => 'Logout successful',
        ], 200);
    }

    /**
     * Get current authenticated user
     */
    public function getCurrentUser(Request $request): JsonResponse
    {
        $user = $request->user();
        $activeSubscription = $user->getActiveSubscription();

        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'driver_limit' => $user->getDriverLimit(),
                'truck_limit' => $user->getTruckLimit(),
                'has_company' => !is_null($user->company_id),
                'company_id' => $user->company_id,
                'onboarding_required' => is_null($user->company_id) && $user->role !== 'admin',
                'active_subscription' => $activeSubscription ? [
                    'id' => $activeSubscription->id,
                    'package' => $activeSubscription->package->name,
                    'status' => $activeSubscription->status,
                    'started_at' => $activeSubscription->started_at,
                    'ends_at' => $activeSubscription->ends_at,
                    'trial_ends_at' => $activeSubscription->trial_ends_at,
                    'trial_active' => $activeSubscription->isOnTrial(),
                    'trial_expired' => $activeSubscription->isTrialExpired(),
                    'trial_days_left' => $activeSubscription->trial_ends_at
                        ? max(0, (int) now()->diffInDays($activeSubscription->trial_ends_at, false))
                        : null,
                    'next_billing_date' => $activeSubscription->next_billing_date,
                ] : null,
                'trial_expired' => $activeSubscription ? $activeSubscription->isTrialExpired() : false,
            ],
            'routing' => $this->buildRoutingState($user),
        ], 200);
    }

    /**
     * Refresh access token
     */
    public function refreshToken(Request $request): JsonResponse
    {
        $newToken = JWTAuth::refresh(JWTAuth::getToken());
        return response()->json([
            'success' => true,
            'message' => 'Token refreshed successfully',
            'token' => $newToken,
        ], 200);
    }
}
