'use client';

import { useState, useCallback } from 'react';
import { getConversationMessages, sendWhatsAppMessage, sendWhatsAppBrochure } from '../service';
import { Conversation, Message } from '../types';

interface UseChatLogicOptions {
  /**
   * The lead_id / conversation.id used as the API key for fetching messages.
   * For the messages page this is the selected conversation's `id` (lead_id as string).
   * For the enquiries lead detail page this is the lead's `params.id`.
   */
  leadId: string | null;
  /** Called after messages are fetched so the consumer can persist them. */
  onMessagesLoaded: (
    leadId: string,
    messages: Message[],
    page: number
  ) => void;
  /** Current user session id (used to determine sent/received direction). */
  sessionUserId?: string | number | null;
  /** Called with the API's read_only flag: true when the lead was assigned to another user (no sending). */
  onReadOnlyChange?: (readOnly: boolean) => void;
}

interface UseChatLogicReturn {
  hasMoreMessages: boolean;
  isLoadingMore: boolean;
  currentPage: number;
  fetchMessages: (page?: number) => Promise<void>;
  loadMoreMessages: () => Promise<void>;
  handleSendMessage: (
    conversationId: string,
    text: string,
    messageType: string,
    onOptimisticUpdate: (msg: Message) => void,
    onConfirmed: (tempId: string, realId: string) => void,
    templateParams?: {
      templateName: string;
      languageCode?: string;
      components?: any[];
      template?: any;
    }
  ) => Promise<void>;
  resetPagination: () => void;
}

/** Shared helper: format a date string as TODAY / YESTERDAY / readable date */
export function formatDisplayDate(dateStr: string): string {
  const dateObj = new Date(dateStr);
  const today = new Date().toDateString();
  const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toDateString();
  const logDateStr = dateObj.toDateString();

  if (logDateStr === today) return 'TODAY';
  if (logDateStr === yesterday) return 'YESTERDAY';

  const parsedDate = new Date(dateStr);
  if (!isNaN(parsedDate.getTime())) {
    return parsedDate.toLocaleDateString('en-GB', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    });
  }
  return dateStr;
}

/** Shared helper: format a Date as "h:mm AM/PM" */
export function formatTimeStr(date: Date): string {
  return date.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
    hour12: true,
  });
}

/** Map a raw API date-group response into an array of Message objects */
export function mapDateGroupsToMessages(
  dateGroups: any[],
  sessionUserId?: string | number | null
): Message[] {
  const mappedMessages: Message[] = [];

  dateGroups.forEach((group: any) => {
    const groupDate = group.date; // e.g. "2026-06-16"

    group.logs.forEach((log: any) => {
      const dateObj = log.created_at ? new Date(log.created_at) : new Date();
      const timeStr = formatTimeStr(dateObj);
      const displayDate = formatDisplayDate(groupDate);
      const isSent =
        sessionUserId && String(log.sender_id) === String(sessionUserId);

      mappedMessages.push({
        id: log.message_id || String(log.id),
        text: log.message || '',
        timestamp: `${displayDate}, ${timeStr}`,
        type: isSent ? 'sent' : 'received',
        message_status: log.message_status || 'sent',
        createdAt: log.created_at || dateObj.toISOString(),
        message_type: log.message_type || log.type,
        fileName: log.filename,
        logId: log.id,
        whatsappMessageId: log.message_id,
      });
    });
  });

  return mappedMessages;
}

/** Merge old + new messages, de-duplicate by id, and sort chronologically */
export function mergeMessages(
  existing: Message[],
  incoming: Message[],
  page: number
): Message[] {
  const base = page === 1 ? incoming : [...incoming, ...existing];
  const uniqueMap = new Map<string, Message>();
  base.forEach((m) => uniqueMap.set(m.id, m));
  const merged = Array.from(uniqueMap.values());
  merged.sort((a, b) => {
    const tA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const tB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return tA - tB;
  });
  return merged;
}

const PAGE_SIZE = 20;

/**
 * useChatLogic – encapsulates message fetching, pagination, and sending logic
 * shared between the Messages page and the Lead Details chat drawer.
 */
export function useChatLogic({
  leadId,
  onMessagesLoaded,
  sessionUserId,
  onReadOnlyChange,
}: UseChatLogicOptions): UseChatLogicReturn {
  const [hasMoreMessages, setHasMoreMessages] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const resetPagination = useCallback(() => {
    setCurrentPage(1);
    setHasMoreMessages(true);
  }, []);

  const fetchMessages = useCallback(
    async (page: number = 1) => {
      if (!leadId) return;
      try {
        if (page > 1) setIsLoadingMore(true);
        const responseData = await getConversationMessages(
          Number(leadId),
          page,
          PAGE_SIZE
        );
        if (responseData?.success && Array.isArray(responseData.data)) {
          const mapped = mapDateGroupsToMessages(responseData.data, sessionUserId);
          setHasMoreMessages(mapped.length >= PAGE_SIZE);
          onMessagesLoaded(leadId, mapped, page);
          onReadOnlyChange?.(responseData.read_only === true);
        } else {
          if (page > 1) setHasMoreMessages(false);
        }
      } catch (err) {
        console.error('Failed to fetch conversation messages:', err);
        if (page > 1) setHasMoreMessages(false);
      } finally {
        setIsLoadingMore(false);
      }
    },
    [leadId, sessionUserId, onMessagesLoaded, onReadOnlyChange]
  );

  const loadMoreMessages = useCallback(async () => {
    if (!hasMoreMessages || isLoadingMore || !leadId) return;
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    await fetchMessages(nextPage);
  }, [hasMoreMessages, isLoadingMore, leadId, currentPage, fetchMessages]);

  /**
   * Send a WhatsApp message.
   *
   * @param conversationId  The lead_id as a string (matches Conversation.id)
   * @param text            The message body
   * @param messageType     'text' | 'template'
   * @param onOptimisticUpdate  Called immediately with a temp message for snappy UI
   * @param onConfirmed     Called once the API returns the real message_id
   */
  const handleSendMessage = useCallback(
    async (
      conversationId: string,
      text: string,
      messageType: string,
      onOptimisticUpdate: (msg: Message) => void,
      onConfirmed: (tempId: string, realId: string) => void,
      templateParams?: {
        templateName: string;
        languageCode?: string;
        components?: any[];
        template?: any;
      }
    ) => {
      const now = new Date();
      const timeStr = formatTimeStr(now);
      const tempId = `m${Date.now()}`;

      const optimisticMsg: Message = {
        id: tempId,
        text,
        timestamp: `TODAY, ${timeStr}`,
        type: 'sent',
        message_status: 'sent',
        createdAt: now.toISOString(),
        message_type: messageType || 'text',
      };

      onOptimisticUpdate(optimisticMsg);

      try {
        let responseData;
        if (messageType === 'template' && templateParams?.templateName && !templateParams?.template) {
          responseData = await sendWhatsAppBrochure(
            conversationId,
            templateParams.templateName
          );
        } else {
          responseData = await sendWhatsAppMessage({
            lead_id: Number(conversationId),
            message: text,
            message_type: messageType || 'text',
            template: templateParams?.template,
          });
        }

        if (responseData?.success) {
          const realId = responseData.message_id || responseData.data?.messageId || responseData.data?.id || `gb_${Date.now()}`;
          onConfirmed(tempId, realId);
        }
      } catch (err) {
        console.error('Failed to send WhatsApp message via API:', err);
      }
    },
    []
  );

  return {
    hasMoreMessages,
    isLoadingMore,
    currentPage,
    fetchMessages,
    loadMoreMessages,
    handleSendMessage,
    resetPagination,
  };
}
