<?php

namespace App\Http\Controllers\Api\Admin;

use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    /**
     * Get all users with filters
     */
    public function index(Request $request): JsonResponse
    {
        $query = User::query();

        // Filter by role
        if ($request->has('role')) {
            $query->where('role', $request->role);
        }

        // Filter by status
        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        // Search
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // Sort
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $users = $query->paginate(15);

        return response()->json($users);
    }

    /**
     * Get single user
     */
    public function show(User $user): JsonResponse
    {
        $user->loadCount(['listings', 'reservations']);

        return response()->json([
            'user' => $user,
        ]);
    }

    /**
     * Update user
     */
    public function update(Request $request, User $user): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:255'],
            'email' => ['sometimes', 'email', 'unique:users,email,' . $user->id],
            'phone' => ['nullable', 'string', 'max:20'],
            'role' => ['sometimes', 'in:customer,boat_owner,admin'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $user->update($validated);

        return response()->json([
            'message' => 'Kullanıcı güncellendi',
            'user' => $user->fresh(),
        ]);
    }

    /**
     * Toggle user status
     */
    public function toggleStatus(User $user): JsonResponse
    {
        // Prevent deactivating yourself
        if ($user->id === request()->user()->id) {
            return response()->json([
                'message' => 'Kendinizi devre dışı bırakamazsınız.',
            ], 422);
        }

        $user->update(['is_active' => !$user->is_active]);

        // Revoke tokens if deactivated
        if (!$user->is_active) {
            $user->tokens()->delete();
        }

        return response()->json([
            'message' => $user->is_active ? 'Kullanıcı aktifleştirildi' : 'Kullanıcı devre dışı bırakıldı',
            'user' => $user,
        ]);
    }

    /**
     * Create new user
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users'],
            'phone' => ['nullable', 'string', 'max:20'],
            'password' => ['required', 'string', 'min:8'],
            'role' => ['required', 'in:customer,boat_owner,admin'],
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?? null,
            'password' => Hash::make($validated['password']),
            'role' => $validated['role'],
            'is_active' => true,
            'email_verified_at' => now(),
        ]);

        return response()->json([
            'message' => 'Kullanıcı oluşturuldu',
            'user' => $user,
        ], 201);
    }

    /**
     * Delete user
     */
    public function destroy(User $user): JsonResponse
    {
        // Prevent deleting yourself
        if ($user->id === request()->user()->id) {
            return response()->json([
                'message' => 'Kendinizi silemezsiniz.',
            ], 422);
        }

        // Check for active listings or reservations
        $hasActiveListings = $user->listings()->where('status', 'active')->exists();
        $hasActiveReservations = $user->reservations()->whereIn('status', ['pending', 'approved'])->exists();

        if ($hasActiveListings || $hasActiveReservations) {
            return response()->json([
                'message' => 'Aktif ilanları veya rezervasyonları olan kullanıcı silinemez.',
            ], 422);
        }

        $user->tokens()->delete();
        $user->delete();

        return response()->json([
            'message' => 'Kullanıcı silindi',
        ]);
    }
}
