'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Input, Spin } from 'antd';
import { SearchOutlined, CheckOutlined } from '@ant-design/icons';
import { Conversation } from '@/app/messages/types';

interface ConversationListProps {
  conversations: Conversation[];
  selectedId: string | null;
  onSelect: (id: string) => void;
  search: string;
  onSearchChange: (value: string) => void;
  hasMore: boolean;
  isLoadingMore: boolean;
  onLoadMore: () => void;
}

type FilterType = 'all' | 'read' | 'unread';

const ConversationList: React.FC<ConversationListProps> = ({
  conversations,
  selectedId,
  onSelect,
  search,
  onSearchChange,
  hasMore,
  isLoadingMore,
  onLoadMore,
}) => {
  console.log("selectedId  ", selectedId)
  const [filter, setFilter] = useState<FilterType>('all');

  // ── Infinite scroll sentinel ──────────────────────────────────────────────
  const sentinelRef = useRef<HTMLDivElement>(null);
  // Keep refs up-to-date on every render so the observer never uses stale values
  const hasMoreRef = useRef(hasMore);
  const onLoadMoreRef = useRef(onLoadMore);
  useEffect(() => {
    hasMoreRef.current = hasMore;
    onLoadMoreRef.current = onLoadMore;
  });

  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMoreRef.current) {
          onLoadMoreRef.current();
        }
      },
      { threshold: 0.1 }
    );
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, []); // set up once; refs handle latest values

  const unreadCount = conversations.filter((c) => !c.isRead).length;

  const filtered = conversations.filter((c) => {
    const matchesSearch = c.name.toLowerCase().includes(search.toLowerCase());
    const matchesFilter =
      filter === 'all' ? true : filter === 'read' ? c.isRead : !c.isRead;
    return matchesSearch && matchesFilter;
  });

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map((n) => n[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  const getAvatarColor = (name: string) => {
    const colors = [
      '#0e8744', '#184b73', '#e67e22', '#8e44ad',
      '#2980b9', '#c0392b', '#27ae60', '#d35400',
    ];
    const index = name.charCodeAt(0) % colors.length;
    return colors[index];
  };

  const formatLastMessageTime = (conv: Conversation) => {
    const latestMsg = conv.messages[conv.messages.length - 1];
    const timestampStr = latestMsg?.createdAt || latestMsg?.timestamp || conv.lastMessageTime;

    if (!timestampStr) return conv.lastMessageTime || '';

    let dateObjObj: Date;
    try {
      if (timestampStr.includes('T') || /^\d{4}-\d{2}-\d{2}/.test(timestampStr) || !isNaN(Date.parse(timestampStr))) {
        dateObjObj = new Date(timestampStr);
      } else {
        return conv.lastMessageTime || timestampStr;
      }
    } catch (e) {
      return conv.lastMessageTime || timestampStr;
    }

    if (isNaN(dateObjObj.getTime())) {
      return conv.lastMessageTime || timestampStr;
    }

    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
    const msgDate = new Date(dateObjObj.getFullYear(), dateObjObj.getMonth(), dateObjObj.getDate());

    if (msgDate.getTime() === today.getTime()) {
      return dateObjObj.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      });
    } else if (msgDate.getTime() === yesterday.getTime()) {
      return 'Yesterday';
    } else {
      const day = String(dateObjObj.getDate()).padStart(2, '0');
      const month = String(dateObjObj.getMonth() + 1).padStart(2, '0');
      const year = dateObjObj.getFullYear();
      return `${day}/${month}/${year}`;
    }
  };

  return (
    <div className="wa-conversation-list">
      <div className="wa-list-header">
        <h2 className="wa-list-title">Messages</h2>
      </div>

      {/* Search */}
      <div className="wa-search-wrapper">
        <Input
          suffix={<SearchOutlined className="wa-search-icon" />}
          placeholder="Search by name"
          value={search}
          onChange={(e) => onSearchChange(e.target.value)}
          className="wa-search-input"
          id="wa-search-input"
        />
      </div>

      {/* Filter Tabs */}
      <div className="wa-filter-tabs">
        <div className="wa-filter-title">Recent</div>
      </div>

      {/* Conversation Items */}
      <div className="wa-conversation-items">
        {filtered.length === 0 ? (
          <div className="wa-no-results">No conversations found</div>
        ) : (
          filtered.map((conv) => (
            <div
              key={conv.id}
              id={`wa-conv-${conv.id}`}
              className={`
    wa-conversation-item
    ${!conv.isRead && selectedId !== conv.id ? 'wa-conversation-item--unopened' : ''}
    ${selectedId === conv.id ? 'wa-conversation-item--active' : ''}
  `}
              onClick={() => onSelect(conv.id)}
            >
              <div className="wa-conv-info">
                <div className="wa-conv-top-row">
                  <span
                    className={`wa-conv-name ${conv.unreadCount > 0 ? 'wa-conv-name--unread' : ''
                      }`}
                  >
                    {conv.name}


                  </span>
                  <span>
                    {/* You are the sender */}
                    <span></span>
                    <span className="wa-conv-time">{formatLastMessageTime(conv)}</span>
                  </span>
                </div>
                <div className="wa-conv-bottom-row">
                  <span className="wa-conv-preview">

                    {conv.lastMessage}

                  </span>
                  <span>
                    {Number(conv.unreadCount) === 0 && conv.last_message_sender_type === 'user' && (
                      conv.message_status === 'read' ? (
                        <span className="wa-tick-read">
                          <img src="/svg/check-active.svg" />
                        </span>
                      ) : conv.message_status === 'delivered' ? (
                        <span className="wa-tick-status wa-tick-status--delivered">
                          <img src="/svg/check.svg" />
                        </span>
                      ) : (
                        <span className="wa-tick-status">
                          <CheckOutlined />
                        </span>
                      )
                    )}
                  </span>
                  {conv.unreadCount > 0 && (
                    <span className="wa-unread-dot">{conv.unreadCount}</span>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
        {/* Infinite scroll sentinel – triggers load-more when scrolled into view */}
        <div ref={sentinelRef} style={{ height: 1 }}>
          {isLoadingMore && (
            <div className="wa-load-more-spinner">
              <Spin size="small" />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ConversationList;
