import React, { useState, useCallback, useEffect } from "react";
import { ChatChannelItem } from "./ChatChannelItem";

const isItemPinned = (item) =>
  Boolean(item?.isPinned ?? item?.otherProps?.is_pinned);

export const ChatChannelList = ({
  channels,
  selectedChannelOrChatId,
  onChannelSelect,
  showChannelList,
  showCheckbox,
  handleChatSelect,
  selectedChat = [],
  onPinnedChatClick,
  handleToast,
}) => {
  // Local overrides so list re-sorts immediately when user pins/unpins
  const [pinnedOverrides, setPinnedOverrides] = useState({});

  // Clear overrides when parent updates channels so we stay in sync
  useEffect(() => {
    if (!Array.isArray(channels)) return;
    setPinnedOverrides((prev) => {
      let changed = false;
      const next = { ...prev };
      channels.forEach((ch) => {
        if (ch?.id != null && prev[ch.id] !== undefined && isItemPinned(ch) === Boolean(prev[ch.id])) {
          delete next[ch.id];
          changed = true;
        }
      });
      return changed ? next : prev;
    });
  }, [channels]);

  const getEffectivePinned = useCallback(
    (item) => {
      if (item?.id != null && pinnedOverrides.hasOwnProperty(item.id)) {
        return Boolean(pinnedOverrides[item.id]);
      }
      return isItemPinned(item);
    },
    [pinnedOverrides]
  );

  const handlePinnedChange = useCallback((chatId, newPinned) => {
    setPinnedOverrides((prev) => ({ ...prev, [chatId]: newPinned }));
  }, []);

  const sortedChannels = Array.isArray(channels)
    ? [...channels].sort((a, b) => {
        const aPinned = getEffectivePinned(a);
        const bPinned = getEffectivePinned(b);
        if (aPinned === bPinned) return 0;
        return aPinned ? -1 : 1;
      })
    : [];

  return (
    <div className="chat-channel-list">
      {sortedChannels.length > 0 ? (
        sortedChannels.map((channel, index) => (
          <ChatChannelItem
            key={channel.id}
            {...channel}
            isPinned={getEffectivePinned(channel)}
            onPinnedChatClick={onPinnedChatClick}
            onPinnedChange={handlePinnedChange}
            isSelected={channel.id === selectedChannelOrChatId}
            onClick={(e) => onChannelSelect(channel?.id, channel)}
            showChannelList={showChannelList}
            showCheckbox={showCheckbox}
            handleChatSelect={handleChatSelect}
            selectedChat={selectedChat}
            handleToast={handleToast}
          />
        ))
      ) : (
        <div className="no-channels-found-container">
          <p className="no-channels-found">No {showChannelList?"Channels":"Chats"} found</p>
          <p className="no-channels-found-description">
           Please create a new {showChannelList?"channel":"chat"} to get started.
          </p>
        </div>
      )}
    </div>
  );
};
