<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Services\UserService;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminUserController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;
    
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    /**
     * Display a listing of users
     */
    public function index(Request $request)
    {
        $filters = [
            'role_type' => $request->input('role_type'),
            'status' => $request->input('status'),
            'search' => $request->input('search'),
            'sort_by' => $request->input('sort_by', 'created_at'),
            'sort_order' => $request->input('sort_order', 2),
        ];

        $perPage = $request->input('per_page', 5);
        $currentPage = $request->input('page', 1);
        
        $query = \App\Models\User::query();

        // Apply filters
        if ($filters['role_type']) {
            $query->where('role_type', $filters['role_type']);
        }
        if ($filters['status']) {
            $query->where('status', $filters['status']);
        }
        if ($filters['search']) {
            $search = $filters['search'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // Apply sorting
        $sortBy = $filters['sort_by'];
        $sortOrder = $filters['sort_order'] === 1 ? 'asc' : 'desc';
        $query->orderBy($sortBy, $sortOrder);

        // Get paginated results
        $users = $query->paginate($perPage, ['*'], 'page', $currentPage);
        
        // Calculate starting serial number for current page
        $startSN = (($currentPage - 1) * $perPage) + 1;
        
        $formattedUsers = $users->map(function ($user, $index) use ($startSN) {
            return [
                'id' => $user->id, 
                'sn' => $startSN + $index, 
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'role_type' => $user->role_type,
                'role' => match($user->role_type) {
                    1 => 'Landlord',
                    2 => 'Tenant',
                    3 => 'Admin',
                    default => 'Unknown'
                },
                'status' => match($user->status) {
                    1 => 'active',
                    2 => 'inactive',
                    3 => 'suspended',
                    default => 'unknown'
                },
                'status_badge' => match($user->status) {
                    1 => 'success',
                    2 => 'warning',
                    3 => 'danger',
                    default => 'secondary'
                },
                'created_at' => $user->created_at->format('Y-m-d'),
            ];
        });

        return Inertia::render('Admin/Users/User', [
            'users' => $formattedUsers,
            'pagination' => [
                'current_page' => $users->currentPage(),
                'per_page' => $users->perPage(),
                'total' => $users->total(),
                'last_page' => $users->lastPage(),
                'from' => $users->firstItem(),
                'to' => $users->lastItem(),
                'links' => $users->linkCollection()->toArray(),
            ],
            'filters' => $filters,
        ]);
    }

    /**
     * Show the form for creating a new user
     */
    public function create()
    {
        return Inertia::render('Admin/Users/create/User');
    }

    /**
     * Store a newly created user
     */
    public function store(StoreUserRequest $request)
    {
        try {
            $this->userService->createUserByAdmin($request->validated(), auth()->user());

            return redirect()->route('admin.users.index')
                ->with('success', ['message' => 'User created successfully.']);
        } catch (\Exception $e) {
            return back()->withErrors(['message' => $e->getMessage()]);
        }
    }

    /**
     * Get user details for editing
     */
    public function edit($id)
    {
        $user = $this->userService->getUserById($id);

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

        return response()->json([
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'role_type' => $user->role_type,
            'status' => $user->status,
            'profile_photo' => $user->profile_photo,
        ]);
    }

    /**
     * Update the specified user
     */
    public function update(UpdateUserRequest $request, $id)
    {
        try {
            $result = $this->userService->updateUser($id, $request->validated(), auth()->user());

            if (!$result) {
                return back()->withErrors(['message' => 'User not found.']);
            }

            return back()->with('success', ['message' => 'User updated successfully.']);
        } catch (\Exception $e) {
            return back()->withErrors(['message' => $e->getMessage()]);
        }
    }

    /**
     * Remove the specified user
     */
    public function destroy($id)
    {
        try {
            $user = $this->userService->getUserById($id);

            if (!$user) {
                return $this->error('User not found');
            }

            // Prevent deleting own account
            if ($user->id === auth()->id()) {
                return $this->error('You cannot delete your own account');
            }

            // Use the trait for consistent deletion handling
            return $this->deleteModel($id, new User());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * Display pending landlords
     */
    public function pendingLandlords()
    {
        try {
            $pendingLandlords = $this->userService->getPendingLandlords();
            
            // Format data for display - now getPendingLandlords returns flat structure
            $formattedLandlords = array_map(function ($landlord, $index) {
                // Handle both nested structure (from API) and flat structure (from service)
                $userData = is_array($landlord) && isset($landlord['user']) ? $landlord['user'] : $landlord;
                
                // Ensure userData is an array and has required fields
                if (!is_array($userData)) {
                    return null;
                }
                
                return [
                    'id' => $userData['id'] ?? null,
                    'sn' => $index + 1,
                    'name' => $userData['name'] ?? 'N/A',
                    'email' => $userData['email'] ?? 'N/A',
                    'phone' => $userData['phone'] ?? 'N/A',
                    'status' => 'inactive',
                    'status_badge' => 'warning',
                    'created_at' => isset($userData['created_at']) 
                        ? (is_string($userData['created_at']) 
                            ? date('Y-m-d', strtotime($userData['created_at'])) 
                            : $userData['created_at']->format('Y-m-d'))
                        : 'N/A',
                ];
            }, $pendingLandlords, array_keys($pendingLandlords));

            // Filter out null values in case of data issues
            $formattedLandlords = array_filter($formattedLandlords, function($item) {
                return $item !== null;
            });

            return Inertia::render('Admin/Users/PendingLandlords', [
                'landlords' => array_values($formattedLandlords), // Re-index array
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load pending landlords: ' . $e->getMessage());
        }
    }

    /**
     * Approve a landlord
     */
    public function approveLandlord($id)
    {
        try {
            $user = $this->userService->getUserById($id);
            
            if (!$user) {
                return $this->error('User not found');
            }

            if ($user->role_type !== 1) {
                return $this->error('User is not a landlord');
            }

            if ($user->status === 1) {
                return $this->error('Landlord is already approved');
            }

            $this->userService->updateUserStatus($user, 1); // 1=ACTIVE

            return redirect()->route('admin.users.pending-landlords')
                ->with('success', ['message' => 'Landlord approved successfully.']);
        } catch (\Exception $e) {
            return $this->error('Failed to approve landlord: ' . $e->getMessage());
        }
    }

    /**
     * Reject a landlord
     */
    public function rejectLandlord($id)
    {
        try {
            $user = $this->userService->getUserById($id);
            
            if (!$user) {
                return $this->error('User not found');
            }

            if ($user->role_type !== 1) {
                return $this->error('User is not a landlord');
            }

            $this->userService->updateUserStatus($user, 3); // 3=SUSPENDED

            return redirect()->route('admin.users.pending-landlords')
                ->with('success', ['message' => 'Landlord rejected successfully.']);
        } catch (\Exception $e) {
            return $this->error('Failed to reject landlord: ' . $e->getMessage());
        }
    }
}
