<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ChatMessage;
use App\Models\User;
use App\Services\FirebaseChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChatController extends Controller
{
    protected $firebaseChatService;

    public function __construct(FirebaseChatService $firebaseChatService)
    {
        $this->firebaseChatService = $firebaseChatService;
    }
    /**
     * Get list of conversations for authenticated user
     */
    public function index(Request $request)
    {
        try {
            $userId = $request->user()->id;

            // Get unique conversations with latest message
            $conversations = ChatMessage::select('chat_messages.*')
                ->where(function($query) use ($userId) {
                    $query->where('sender_id', $userId)
                          ->orWhere('receiver_id', $userId);
                })
                ->with(['sender', 'receiver', 'ad'])
                ->orderBy('created_at', 'desc')
                ->get()
                ->groupBy(function($message) use ($userId) {
                    // Group by the other user's ID
                    return $message->sender_id == $userId 
                        ? $message->receiver_id 
                        : $message->sender_id;
                })
                ->map(function($messages, $otherUserId) use ($userId) {
                    $latestMessage = $messages->first();
                    $otherUser = $latestMessage->sender_id == $userId 
                        ? $latestMessage->receiver 
                        : $latestMessage->sender;
                    
                    // Count unread messages from this user
                    $unreadCount = ChatMessage::where('sender_id', $otherUserId)
                        ->where('receiver_id', $userId)
                        ->whereNull('read_at')
                        ->count();

                    return [
                        'user_id' => $otherUser->id,
                        'user_name' => $otherUser->name,
                        'user_avatar' => $otherUser->avatar_url ?? null,
                        'last_message' => $latestMessage->message,
                        'last_message_time' => $latestMessage->created_at->toIso8601String(),
                        'unread_count' => $unreadCount,
                        'ad_id' => $latestMessage->ad_id,
                        'ad_title' => $latestMessage->ad ? $latestMessage->ad->title : null,
                    ];
                })
                ->values();

            return response()->json([
                'success' => true,
                'data' => $conversations,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch conversations',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get messages with a specific user
     */
    public function show(Request $request, $userId)
    {
        try {
            $currentUserId = $request->user()->id;

            $messages = ChatMessage::betweenUsers($currentUserId, $userId)
                ->with(['sender', 'receiver', 'ad'])
                ->orderBy('created_at', 'asc')
                ->get()
                ->map(function($message) use ($currentUserId) {
                    return [
                        'id' => $message->id,
                        'sender_id' => $message->sender_id,
                        'receiver_id' => $message->receiver_id,
                        'message' => $message->message,
                        'created_at' => $message->created_at->toIso8601String(),
                        'is_read' => !is_null($message->read_at),
                        'is_mine' => $message->sender_id == $currentUserId,
                        'ad_id' => $message->ad_id,
                        'ad_title' => $message->ad ? $message->ad->title : null,
                    ];
                });

            // Mark all messages from the other user as read
            ChatMessage::where('sender_id', $userId)
                ->where('receiver_id', $currentUserId)
                ->whereNull('read_at')
                ->update(['read_at' => now()]);

            return response()->json([
                'success' => true,
                'data' => $messages,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch messages',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Send a message to a user
     */
    public function sendMessage(Request $request, $userId)
    {
        $request->validate([
            'message' => 'required|string|max:1000',
            'ad_id' => 'nullable|exists:ads,id',
        ]);

        try {
            $currentUserId = $request->user()->id;

            $message = ChatMessage::create([
                'sender_id' => $currentUserId,
                'receiver_id' => $userId,
                'message' => $request->message,
                'ad_id' => $request->ad_id,
                'message_type' => 'text',
            ]);

            $message->load(['sender', 'receiver', 'ad']);

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $message->id,
                    'sender_id' => $message->sender_id,
                    'receiver_id' => $message->receiver_id,
                    'message' => $message->message,
                    'created_at' => $message->created_at->toIso8601String(),
                    'is_read' => false,
                    'is_mine' => true,
                    'ad_id' => $message->ad_id,
                    'ad_title' => $message->ad ? $message->ad->title : null,
                ],
                'message' => 'Message sent successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send message',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Mark a message as read
     */
    public function markAsRead(Request $request, $messageId)
    {
        try {
            $message = ChatMessage::findOrFail($messageId);

            // Only the receiver can mark as read
            if ($message->receiver_id != $request->user()->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }

            $message->update(['read_at' => now()]);

            return response()->json([
                'success' => true,
                'message' => 'Message marked as read',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to mark message as read',
            ], 500);
        }
    }

    /**
     * Delete a message
     */
    public function deleteMessage(Request $request, $messageId)
    {
        try {
            $message = ChatMessage::findOrFail($messageId);
            $userId = $request->user()->id;

            // Mark as deleted for the appropriate user
            if ($message->sender_id == $userId) {
                $message->update(['deleted_by_sender' => true]);
            } elseif ($message->receiver_id == $userId) {
                $message->update(['deleted_by_receiver' => true]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }

            // If both deleted, actually delete the message
            if ($message->deleted_by_sender && $message->deleted_by_receiver) {
                $message->delete();
            }

            return response()->json([
                'success' => true,
                'message' => 'Message deleted successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete message',
            ], 500);
        }
    }

    /**
     * Initialize or get a Firebase chat room
     */
    public function initFirebaseChat(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'ad_id' => 'nullable|exists:ads,id',
        ]);

        try {
            $currentUserId = $request->user()->id;
            $receiverId = $request->receiver_id;

            $chatData = $this->firebaseChatService->initializeChat(
                $currentUserId,
                $receiverId,
                $request->ad_id
            );

            return response()->json([
                'success' => true,
                'data' => $chatData,
                'message' => 'Chat initialized successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to initialize chat',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Send message with Firebase sync and push notification
     */
    public function sendFirebaseMessage(Request $request)
    {
        $request->validate([
            'chat_id' => 'required|string',
            'receiver_id' => 'required|exists:users,id',
            'message' => 'required|string|max:1000',
            'type' => 'nullable|in:text,image,offer',
            'image_url' => 'nullable|url',
        ]);

        try {
            $currentUserId = $request->user()->id;

            $result = $this->firebaseChatService->sendMessage(
                $request->chat_id,
                $currentUserId,
                $request->receiver_id,
                $request->message,
                $request->type ?? 'text',
                $request->image_url
            );

            return response()->json([
                'success' => true,
                'data' => $result,
                'message' => 'Message sent successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send message',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update typing status
     */
    public function updateTypingStatus(Request $request)
    {
        $request->validate([
            'chat_id' => 'required|string',
            'is_typing' => 'required|boolean',
        ]);

        try {
            $currentUserId = $request->user()->id;

            $result = $this->firebaseChatService->updateTypingStatus(
                $request->chat_id,
                $currentUserId,
                $request->is_typing
            );

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update typing status',
            ], 500);
        }
    }
}
