<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Services\MessageService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class MessageController extends BaseController
{
    public function __construct(
        private MessageService $messageService
    ) {}

    /**
     * Contact a landlord (public – no login required).
     * Requires name and at least one of email or phone.
     */
    public function contactLandlord(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'nullable|required_without:phone|email|max:255',
                'phone' => 'nullable|required_without:email|string|max:50',
                'receiver_id' => 'required|exists:users,id',
                'property_id' => 'nullable|exists:properties,id',
                'message' => 'required|string|min:1|max:2000',
            ]);

            $receiver = User::find($validated['receiver_id']);
            if (!$receiver || $receiver->role_type !== 1) {
                return $this->validationErrorResponse(['receiver_id' => ['The receiver must be a landlord.']]);
            }

            $message = $this->messageService->sendGuestMessage([
                'name' => $validated['name'],
                'email' => $validated['email'] ?? null,
                'phone' => $validated['phone'] ?? null,
                'receiver_id' => $validated['receiver_id'],
                'property_id' => $validated['property_id'] ?? null,
                'message' => $validated['message'],
            ]);

            return $this->successResponse(
                $this->messageService->formatMessageForResponse($message),
                'Message sent successfully',
                201
            );
        } catch (ValidationException $e) {
            return $this->validationErrorResponse($e->errors());
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to send message: ' . $e->getMessage());
        }
    }

    /**
     * Send a message (authenticated user)
     */
    public function send(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'receiver_id' => 'required|exists:users,id',
                'property_id' => 'nullable|exists:properties,id',
                'message' => 'required|string|min:1|max:2000',
            ]);

            $user = Auth::user();
            $data = $request->only(['receiver_id', 'property_id', 'message']);

            $message = $this->messageService->sendMessage($data, $user);

            return $this->successResponse(
                $this->messageService->formatMessageForResponse($message),
                'Message sent successfully',
                201
            );

        } catch (ValidationException $e) {
            return $this->validationErrorResponse($e->errors());
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to send message: ' . $e->getMessage());
        }
    }

    /**
     * Get conversation between two users
     */
    public function getConversation(Request $request, int $userId): JsonResponse
    {
        try {
            $currentUser = Auth::user();
            $propertyId = $request->get('property_id');
            $perPage = $request->get('per_page', 20);

            $conversation = $this->messageService->getConversation(
                $currentUser->id,
                $userId,
                $propertyId,
                $perPage
            );

            return $this->successResponse($conversation, 'Conversation retrieved successfully');

        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve conversation: ' . $e->getMessage());
        }
    }

    /**
     * Get user's conversations list
     */
    public function getConversations(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $perPage = $request->get('per_page', 15);

            $conversations = $this->messageService->getUserConversations($user->id, $perPage);

            return $this->successResponse($conversations, 'Conversations retrieved successfully');

        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve conversations: ' . $e->getMessage());
        }
    }

    /**
     * Mark messages as read
     */
    public function markAsRead(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'sender_id' => 'nullable|exists:users,id',
                'property_id' => 'nullable|exists:properties,id',
            ]);

            $user = Auth::user();
            $senderId = $request->get('sender_id');
            $propertyId = $request->get('property_id');

            $markedCount = $this->messageService->markAsRead($user->id, $senderId, $propertyId);

            return $this->successResponse([
                'marked_count' => $markedCount,
            ], 'Messages marked as read successfully');

        } catch (ValidationException $e) {
            return $this->validationErrorResponse($e->errors());
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to mark messages as read: ' . $e->getMessage());
        }
    }

    /**
     * Get unread message count
     */
    public function getUnreadCount(): JsonResponse
    {
        try {
            $user = Auth::user();
            $count = $this->messageService->getUnreadCount($user->id);

            return $this->successResponse([
                'unread_count' => $count,
            ], 'Unread count retrieved successfully');

        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to get unread count: ' . $e->getMessage());
        }
    }

    /**
     * Get message statistics
     */
    public function getStatistics(): JsonResponse
    {
        try {
            $user = Auth::user();
            $stats = $this->messageService->getMessageStatistics($user->id);

            return $this->successResponse($stats, 'Message statistics retrieved successfully');

        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to get statistics: ' . $e->getMessage());
        }
    }
}