'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { Spin } from 'antd';
import { useSession } from 'next-auth/react';
import { io } from 'socket.io-client';
import { useDebounce } from 'use-debounce';
import ConversationList from './components/ConversationList';
import ChatView from './components/ChatView';
import { Conversation, Message } from '@/app/messages/types';
import { getConversations } from './service';
import { useChatLogic, formatTimeStr, formatDisplayDate, mergeMessages } from './components/useChatLogic';
import { useWhatsAppSocket } from './components/useWhatsAppSocket';

/** Moves the conversation with the given id to position 0 in the list. */
const bringToTop = (list: Conversation[], id: string): Conversation[] => {
  const idx = list.findIndex((c) => c.id === id);
  if (idx <= 0) return list; // already on top or not found
  return [list[idx], ...list.slice(0, idx), ...list.slice(idx + 1)];
};

const MessagesPage: React.FC = () => {
  const { data: session } = useSession();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [isMobileChatOpen, setIsMobileChatOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [debouncedSearch] = useDebounce(search, 500);
  const [convPage, setConvPage] = useState(1);
  const [hasMoreConvs, setHasMoreConvs] = useState(false);
  const [isLoadingMoreConvs, setIsLoadingMoreConvs] = useState(false);
  const PAGE_LIMIT = 20;

  // ─── Conversation list fetching ───────────────────────────────────────────

  const fetchConversations = async (searchQuery = '', page = 1, append = false, showLoading = true) => {
    try {
      if (append) {
        setIsLoadingMoreConvs(true);
      } else if (showLoading) {
        setLoading(true);
      }
      const responseData = await getConversations(searchQuery, page, PAGE_LIMIT);
      if (responseData?.success && Array.isArray(responseData.data)) {
        const dbConvs = responseData.data;

        // If the API returned a full page, there may be more
        setHasMoreConvs(dbConvs.length === PAGE_LIMIT);

        const mapped: Conversation[] = dbConvs.map((dbConv: any) => {
          const dateObj = dbConv.updated_at ? new Date(dbConv.updated_at) : new Date();
          const timeStr = formatTimeStr(dateObj);
          const displayDate = formatDisplayDate(dateObj.toISOString().split('T')[0]);

          const messages: Message[] = dbConv.last_message
            ? [
              {
                id: dbConv.last_message_id || `m_${dbConv.id}_${dateObj.getTime()}`,
                text: dbConv.last_message,
                timestamp: `${displayDate}, ${timeStr}`,
                type: dbConv.last_message_sender_type === 'lead' ? 'received' : 'sent',
                message_status: dbConv.message_status || 'sent',
                createdAt: dbConv.updated_at || dateObj.toISOString(),
              } as Message,
            ]
            : [];

          return {
            id: String(dbConv.lead_id),
            name: dbConv.lead_name || `Lead #${dbConv.lead_id}`,
            phone: '',
            lastMessage: dbConv.last_message || '',
            lastMessageTime: timeStr,
            unreadCount: dbConv?.unread_count || 0,
            isRead:
              dbConv.message_status === 'read' ||
              dbConv.last_message_sender_type === 'lead',
            messages,
            dbId: dbConv.id,
            last_message_sender_type: dbConv.last_message_sender_type,
            message_status: dbConv.message_status,
          };
        });

        if (append) {
          // Append new page, deduplicate by id to avoid duplicates from real-time reordering
          setConversations((prev) => {
            const existingIds = new Set(prev.map((c) => c.id));
            const newConvs = mapped
              .filter((newC) => !existingIds.has(newC.id))
              .map((newC) => {
                const existing = prev.find((oldC) => oldC.id === newC.id);
                if (existing && existing.messages.length > 1) {
                  return { ...newC, messages: existing.messages };
                }
                return newC;
              });
            return [...prev, ...newConvs];
          });
        } else {
          // Preserve already-fetched full message history for open conversations
          setConversations((prev) =>
            mapped.map((newC) => {
              const existing = prev.find((oldC) => oldC.id === newC.id);
              if (existing && existing.messages.length > 1) {
                return { ...newC, messages: existing.messages };
              }
              return newC;
            })
          );
        }
      }
    } catch (err: any) {
      console.error('Failed to fetch WhatsApp conversations from API:', err);
    } finally {
      if (append) {
        setIsLoadingMoreConvs(false);
      } else if (showLoading) {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    // Reset to page 1 whenever the search query changes
    setConvPage(1);
    setHasMoreConvs(false);
    fetchConversations(debouncedSearch, 1, false, true);
  }, [debouncedSearch]);

  const loadMoreConversations = () => {
    if (!hasMoreConvs || isLoadingMoreConvs) return;
    const nextPage = convPage + 1;
    setConvPage(nextPage);
    fetchConversations(debouncedSearch, nextPage, true, false);
  };

  // Broadcast unread count to the rest of the app
  useEffect(() => {
    const unreadConversations = conversations.filter((c) => (c.unreadCount || 0) > 0).length;
    window.dispatchEvent(
      new CustomEvent('whatsapp_unread_count_update', { detail: unreadConversations })
    );
  }, [conversations]);

  // ─── useChatLogic hook ────────────────────────────────────────────────────

  /**
   * Called by the hook after messages are fetched.
   * Merges them into the conversation in state.
   */
  const handleMessagesLoaded = useCallback(
    (leadId: string, incoming: Message[], page: number) => {
      setConversations((prev) =>
        prev.map((c) => {
          if (c.id === leadId) {
            const merged = mergeMessages(c.messages, incoming, page);
            return { ...c, messages: merged };
          }
          return c;
        })
      );
    },
    []
  );

  const {
    hasMoreMessages,
    isLoadingMore,
    fetchMessages,
    loadMoreMessages,
    resetPagination,
  } = useChatLogic({
    leadId: selectedId,
    onMessagesLoaded: handleMessagesLoaded,
    sessionUserId: session?.user?.id,
  });

  // Fetch messages whenever a conversation is selected
  useEffect(() => {
    if (!selectedId) return;
    const selectedConv = conversations.find((c) => c.id === selectedId);
    if (!selectedConv || !selectedConv.dbId) return;
    resetPagination();
    fetchMessages(1);
  }, [selectedId, session?.user?.id]);


  const handleMessageSent = useCallback(
    (conversationId: string, msg: Message) => {
      setConversations((prev) => {
        const updated = prev.map((c) => {
          if (c.id === conversationId) {
            const messageExists = c.messages.some((m) => m.id === msg.id);
            const updatedMessages = messageExists
              ? c.messages
              : [...c.messages, msg];
            return {
              ...c,
              lastMessage: msg.text,
              lastMessageTime: msg.timestamp.includes(',')
                ? msg.timestamp.split(',')[1]?.trim() || ''
                : msg.timestamp,
              last_message_sender_type: 'user',
              message_status: msg.message_status,
              isRead: true,
              unreadCount: 0,
              messages: updatedMessages,
            };
          }
          return c;
        });
        return bringToTop(updated, conversationId);
      });
    },
    []
  );

  // ─── Socket.io – real-time updates ───────────────────────────────────────
  const handleSocketMessage = useCallback((convId: string | number, leadId: string | number, newMsg: Message, log: any) => {
    setConversations((prev) => {
      const exists = prev.some((c) => c.dbId === convId || c.id === String(leadId));
      if (!exists) {
        fetchConversations(search, 1, false, false);
        return prev;
      }

      const activeLeadId = String(leadId);
      const updated = prev.map((c) => {
        if (c.dbId === convId || c.id === activeLeadId) {
          const isCurrent = c.id === selectedId;
          const isMessageSent = newMsg.type === 'sent';

          const messageExists = c.messages.some((m) => m.id === newMsg.id);
          const updatedMessages = messageExists
            ? c.messages
            : [...c.messages, newMsg];

          return {
            ...c,
            lastMessage: log.message || '',
            lastMessageTime: newMsg.timestamp.includes(',')
              ? newMsg.timestamp.split(',')[1]?.trim() || ''
              : newMsg.timestamp,
            last_message_sender_type: isMessageSent ? 'user' : 'lead',
            message_status: newMsg.message_status,
            unreadCount: isCurrent ? 0 : !isMessageSent ? c.unreadCount + 1 : c.unreadCount,
            isRead: isCurrent ? true : isMessageSent ? c.isRead : false,
            messages: updatedMessages,
          };
        }
        return c;
      });
      return bringToTop(updated, activeLeadId);
    });
  }, [search, selectedId, fetchConversations]);

  const handleSocketStatus = useCallback((conversation_id: string | number, message_id: string, status: string) => {
    setConversations((prev) =>
      prev.map((c) => {
        if (c.dbId === conversation_id) {
          return {
            ...c,
            message_status: status as any, // optimistically update list snippet status
          };
        }
        return c;
      })
    );
  }, []);

  useWhatsAppSocket({
    sessionUserId: session?.user?.id,
    onMessageReceived: handleSocketMessage,
    onStatusUpdated: handleSocketStatus,
  });


  // ─── Conversation selection ───────────────────────────────────────────────

  const selectedConversation =
    conversations.find((c) => c.id === selectedId) ?? null;

  const handleSelectConversation = (id: string) => {
    setSelectedId(id);
    setIsMobileChatOpen(true);
    // Mark as read immediately in UI
    setConversations((prev) =>
      prev.map((c) => (c.id === id ? { ...c, isRead: true, unreadCount: 0 } : c))
    );
  };

  // ─── Render ───────────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div
        className="wa-page"
        id="wa-messages-page"
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          width: '100%',
        }}
      >
        <Spin size="large" tip="Loading conversations..." />
      </div>
    );
  }

  return (
    <div
      className={`wa-page ${isMobileChatOpen ? 'chat-active' : ''}`}
      id="wa-messages-page"
    >
      <ConversationList
        conversations={conversations}
        selectedId={selectedId}
        onSelect={handleSelectConversation}
        search={search}
        onSearchChange={setSearch}
        hasMore={hasMoreConvs}
        isLoadingMore={isLoadingMoreConvs}
        onLoadMore={loadMoreConversations}
      />
      <div className="wa-divider" />
      <ChatView
        leadId={selectedId}
        conversationName={selectedConversation?.name}
        onCloseMobile={() => setIsMobileChatOpen(false)}
        onMessageSent={handleMessageSent}
      />
    </div>
  );
};

export default MessagesPage;
