"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Briefcase, FileText, Info, Wifi, WifiOff, Search } from "lucide-react";
import { sendApplicationMessage, broadcastCompleteMessage } from "@/app/actions/messageActions";
import { ConversationSummary } from "@/app/actions/conversationActions";
import { useRealtimeMessages, RealtimeMessage } from "@/lib/hooks/useRealtimeMessages";

import { ConversationList } from "./ConversationList";
import { MessageThread, ThreadMessage } from "./MessageThread";
import { MessageComposer } from "./MessageComposer";
import { ConversationSidebar, ThreadData } from "./ConversationSidebar";
import { SearchOverlay } from "./SearchOverlay";

interface MessageThreadViewProps {
    thread: ThreadData & { messages: ThreadMessage[]; conversationId?: string };
    conversations: ConversationSummary[];
    currentUserId: string;
    currentUserRole: string;
}

export function MessageThreadView({
    thread,
    conversations,
    currentUserId,
    currentUserRole,
}: MessageThreadViewProps) {
    const router = useRouter();
    const [showSidebar, setShowSidebar] = useState(false);
    const [showSearch, setShowSearch] = useState(false);
    const [localMessages, setLocalMessages] = useState<ThreadMessage[]>(thread.messages);
    const processedIdsRef = useRef<Set<string>>(new Set());

    // Connect to real-time SSE stream
    const {
        newMessages,
        clearMessages,
        typingUsers,
        onlineUsers,
        isConnected,
        sendTyping,
        readReceipts,
        markConversationRead,
        newAttachments,
    } = useRealtimeMessages({
        conversationId: thread.conversationId,
    });

    // Reset local messages when thread changes (navigation)
    useEffect(() => {
        setLocalMessages(thread.messages);
        processedIdsRef.current = new Set(thread.messages.map(m => m.id));
    }, [thread.applicationId, thread.messages]);

    // ─── Mark conversation as read when opened and when new messages arrive ───
    useEffect(() => {
        if (thread.conversationId) {
            markConversationRead(thread.conversationId);
        }
    }, [thread.conversationId, markConversationRead]);

    // Also mark read when we receive new messages from the other user
    useEffect(() => {
        if (newMessages.length > 0 && thread.conversationId) {
            const hasOtherUserMessages = newMessages.some(
                (m) => m.senderId !== currentUserId
            );
            if (hasOtherUserMessages) {
                // Small delay to ensure messages are rendered first
                const timer = setTimeout(() => {
                    markConversationRead(thread.conversationId!);
                }, 500);
                return () => clearTimeout(timer);
            }
        }
    }, [newMessages, thread.conversationId, currentUserId, markConversationRead]);

    // ─── Handle read receipt SSE events → mark our sent messages as "seen" ───
    useEffect(() => {
        if (readReceipts.length === 0) return;

        setLocalMessages((prev) =>
            prev.map((msg) => {
                // Only update our own sent messages
                if (msg.senderId !== currentUserId) return msg;

                // Check if any read receipt includes this message
                const isRead = readReceipts.some((r) =>
                    r.messageIds.includes(msg.id)
                );
                if (isRead && msg.status !== "seen") {
                    return { ...msg, status: "seen" as const, isRead: true };
                }
                return msg;
            })
        );
    }, [readReceipts, currentUserId]);

    // Handle incoming dynamic attachments via SSE
    useEffect(() => {
        if (newAttachments.length === 0) return;

        setLocalMessages((prev) => {
            let updated = false;
            const msgs = prev.map((msg) => {
                const relevantAtts = newAttachments.filter(a => a.messageId === msg.id);
                if (relevantAtts.length > 0) {
                    updated = true;
                    const existingAttIds = new Set(msg.attachments?.map(a => a.id) || []);
                    const unqiueNewAtts = relevantAtts
                        .map(a => a.attachment)
                        .filter(a => !existingAttIds.has(a.id));

                    return {
                        ...msg,
                        attachments: [...(msg.attachments || []), ...unqiueNewAtts]
                    };
                }
                return msg;
            });
            return updated ? msgs : prev;
        });
    }, [newAttachments]);

    // Append real-time messages to local state
    useEffect(() => {
        if (newMessages.length === 0) return;

        const newOnes = newMessages.filter(
            (m) => !processedIdsRef.current.has(m.id)
        );

        if (newOnes.length > 0) {
            setLocalMessages(prev => {
                const combined = [...prev];

                newOnes.forEach(m => {
                    // Check if we already have an optimistic message that this is replacing
                    const existingIdx = combined.findIndex(msg => msg.id === m.id);
                    const existingMsg = existingIdx >= 0 ? combined[existingIdx] : undefined;

                    const convertedMessage: ThreadMessage = {
                        id: m.id,
                        content: m.content,
                        messageType: m.messageType,
                        attachmentUrl: null,
                        senderId: m.senderId,
                        senderName: m.senderName,
                        senderAvatar: m.senderAvatar,
                        senderRole: m.senderRole,
                        isRead: false,
                        createdAt: m.createdAt,
                        // If the stream message doesn't have attachments yet (because they are uploading),
                        // preserve our optimistic attachments so they don't disappear from the UI
                        attachments: m.attachments?.length ? m.attachments : existingMsg?.attachments,
                        status: existingMsg?.status || undefined,
                    };

                    if (existingIdx >= 0) {
                        combined[existingIdx] = convertedMessage;
                    } else {
                        combined.push(convertedMessage);
                    }
                });

                return combined;
            });

            newOnes.forEach((m) => processedIdsRef.current.add(m.id));
            clearMessages();
        }
    }, [newMessages, clearMessages]);

    // Filter typing users for this conversation (exclude self)
    const activeTypingUsers = typingUsers.filter(
        (t) => t.userId !== currentUserId
    );

    // Check if other user is online
    const isOtherUserOnline = onlineUsers.has(thread.otherUser.id);

    // ─── Message Send with Status Tracking ───
    const handleSend = async (content: string, files?: File[]) => {
        const optimisticId = `optimistic_${Date.now()}`;
        const optimisticMsg: ThreadMessage = {
            id: optimisticId,
            content: content.trim(),
            messageType: "text",
            attachmentUrl: null,
            senderId: currentUserId,
            senderName: "You",
            senderAvatar: null,
            senderRole: currentUserRole,
            isRead: false,
            createdAt: new Date().toISOString(),
            status: "sending",
            attachments: files?.map((f, i) => ({
                id: `optimistic_att_${Date.now()}_${i}`,
                filename: f.name,
                fileUrl: URL.createObjectURL(f),
                fileSize: f.size,
                mimeType: f.type,
                thumbnailUrl: f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
            })),
        };
        setLocalMessages((prev) => [...prev, optimisticMsg]);

        try {
            const hasFiles = files && files.length > 0;
            const res = await sendApplicationMessage(thread.applicationId, content, hasFiles);

            if (res.success && res.messageId) {
                // Instantly update the ID so incoming SSE events (like new_attachment) can match it
                processedIdsRef.current.add(res.messageId);
                setLocalMessages((prev) =>
                    prev.map((m) =>
                        m.id === optimisticId
                            ? { ...m, id: res.messageId! }
                            : m
                    )
                );

                // Upload files if any
                if (res.conversationId && hasFiles) {
                    const uploadPromises = files.map(file => {
                        const formData = new FormData();
                        formData.append("file", file);
                        formData.append("messageId", res.messageId!);
                        formData.append("conversationId", res.conversationId!);

                        return fetch("/api/messages/upload", {
                            method: "POST",
                            body: formData,
                        });
                    });

                    // Wait for all file uploads to finish
                    await Promise.allSettled(uploadPromises);

                    // Now broadcast the complete message with exactly its attached files
                    await broadcastCompleteMessage(res.messageId, res.conversationId);
                }

                // Update: sending → sent (after file uploads complete)
                setLocalMessages((prev) =>
                    prev.map((m) =>
                        m.id === res.messageId
                            ? { ...m, status: "sent" as const, attachments: m.attachments }
                            : m
                    )
                );
            } else {
                // Server returned failure
                setLocalMessages((prev) =>
                    prev.map((m) =>
                        m.id === optimisticId || m.id === res.messageId
                            ? { ...m, status: "failed" as const }
                            : m
                    )
                );
            }
        } catch (error) {
            // Mark as failed instead of removing
            setLocalMessages((prev) =>
                prev.map((m) =>
                    m.id === optimisticId
                        ? { ...m, status: "failed" as const }
                        : m
                )
            );
            console.error("Failed to send:", error);
        }
    };

    // ─── Retry Failed Message ───
    const handleRetry = async (messageId: string) => {
        const failedMsg = localMessages.find((m) => m.id === messageId);
        if (!failedMsg) return;

        // Reset status to sending
        setLocalMessages((prev) =>
            prev.map((m) =>
                m.id === messageId ? { ...m, status: "sending" as const } : m
            )
        );

        try {
            const res = await sendApplicationMessage(
                thread.applicationId,
                failedMsg.content
            );

            if (res.success && res.messageId) {
                processedIdsRef.current.add(res.messageId);
                setLocalMessages((prev) =>
                    prev.map((m) =>
                        m.id === messageId
                            ? { ...m, id: res.messageId!, status: "sent" as const }
                            : m
                    )
                );
            } else {
                setLocalMessages((prev) =>
                    prev.map((m) =>
                        m.id === messageId
                            ? { ...m, status: "failed" as const }
                            : m
                    )
                );
            }
        } catch {
            setLocalMessages((prev) =>
                prev.map((m) =>
                    m.id === messageId
                        ? { ...m, status: "failed" as const }
                        : m
                )
            );
        }
    };

    // ─── Delete Failed Message ───
    const handleDeleteFailed = (messageId: string) => {
        setLocalMessages((prev) => prev.filter((m) => m.id !== messageId));
    };

    // Typing handler for composer
    const handleTypingChange = useCallback(
        (isTyping: boolean) => {
            if (thread.conversationId) {
                sendTyping(thread.conversationId, isTyping);
            }
        },
        [thread.conversationId, sendTyping]
    );

    return (
        <div className="flex h-[calc(100vh-120px)] -mt-2 -mx-2 bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
            {/* Left Panel: Conversation List */}
            <ConversationList
                conversations={conversations}
                activeApplicationId={thread.applicationId}
                onlineUsers={onlineUsers}
            />

            {/* Center Panel: Message Thread */}
            <div className="flex-1 flex flex-col min-w-0 bg-slate-50/30">
                {/* Thread Header */}
                <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between bg-white shrink-0 shadow-sm z-10">
                    <div className="flex items-center gap-3">
                        <Link href="/dashboard/messages" className="lg:hidden p-1.5 rounded-lg hover:bg-slate-100 transition-colors">
                            <ArrowLeft className="w-5 h-5 text-slate-500" />
                        </Link>
                        <div className="relative">
                            {thread.otherUser.avatar_url ? (
                                <img src={thread.otherUser.avatar_url} alt="" className="w-10 h-10 rounded-full object-cover border border-slate-100" />
                            ) : (
                                <div className="w-10 h-10 rounded-full bg-primary flex items-center justify-center text-white font-bold text-sm">
                                    {(thread.otherUser.name || "?")[0]?.toUpperCase()}
                                </div>
                            )}
                            {/* Online status dot */}
                            <span
                                className={`absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-white transition-colors ${isOtherUserOnline
                                    ? "bg-emerald-400 animate-pulse"
                                    : "bg-slate-300"
                                    }`}
                            />
                        </div>
                        <div>
                            <div className="flex items-center gap-2">
                                <h2 className="font-bold text-slate-900 text-sm leading-tight">{thread.otherUser.name}</h2>
                                {isOtherUserOnline && (
                                    <span className="text-[10px] text-emerald-500 font-medium">Online</span>
                                )}
                            </div>
                            <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5">
                                <Briefcase className="w-3 h-3" />
                                {currentUserRole === "employer" ? "Candidate for " : "Recruiter · "}
                                <span className="font-medium text-slate-700">{thread.jobTitle}</span>
                            </p>
                        </div>
                    </div>
                    <div className="flex items-center gap-1.5">
                        {/* Connection status indicator */}
                        <div className={`p-2 rounded-lg transition-colors ${isConnected ? "text-emerald-400" : "text-slate-300"}`} title={isConnected ? "Real-time connected" : "Reconnecting..."}>
                            {isConnected ? <Wifi className="w-4 h-4" /> : <WifiOff className="w-4 h-4 animate-pulse" />}
                        </div>
                        <Link
                            href={`/dashboard/applications/${thread.applicationId}`}
                            className="p-2 rounded-lg text-slate-400 hover:text-primary hover:bg-primary/5 transition-colors"
                            title="View Application"
                        >
                            <FileText className="w-5 h-5" />
                        </Link>
                        <button
                            onClick={() => setShowSearch(true)}
                            className="p-2 rounded-lg text-slate-400 hover:text-primary hover:bg-primary/5 transition-colors"
                            title="Search messages"
                        >
                            <Search className="w-5 h-5" />
                        </button>
                        <button
                            onClick={() => setShowSidebar(!showSidebar)}
                            className={`p-2 rounded-lg transition-colors xl:hidden ${showSidebar ? "text-primary bg-primary/5" : "text-slate-400 hover:text-primary hover:bg-primary/5"
                                }`}
                            title="Toggle Details"
                        >
                            <Info className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                {/* Messages Area */}
                <MessageThread
                    messages={localMessages}
                    currentUserId={currentUserId}
                    otherUserName={thread.otherUser.name}
                    jobTitle={thread.jobTitle}
                    typingUsers={activeTypingUsers}
                    onRetry={handleRetry}
                    onDeleteFailed={handleDeleteFailed}
                />

                {/* Compose Area */}
                <MessageComposer
                    onSend={handleSend}
                    placeholder={`Message ${thread.otherUser.name}...`}
                    contextParams={{
                        candidate_name: thread.otherUser.name.split(" ")[0],
                        job_title: thread.jobTitle,
                        company_name: thread.otherUser.company || "Your Company",
                        recruiter_name: currentUserRole === "employer" ? "The Hiring Team" : thread.otherUser.name
                    }}
                    onTypingChange={handleTypingChange}
                    conversationId={thread.conversationId}
                />
            </div>

            {/* Right Panel: Context Sidebar */}
            <div className={`xl:block w-[280px] shrink-0 border-l border-slate-100 bg-white ${showSidebar ? 'block absolute right-0 top-[65px] bottom-0 shadow-2xl z-20 xl:relative xl:top-0 xl:shadow-none' : 'hidden'}`}>
                <ConversationSidebar thread={thread} />
            </div>

            {/* Global/Thread Search Overlay */}
            <SearchOverlay
                isOpen={showSearch}
                onClose={() => setShowSearch(false)}
                conversationId={thread.conversationId}
            />
        </div>
    );
}
