import React, { useEffect, useMemo, useRef, useState } from "react";
import CloseIcon from "../../assets/close.svg";
import { Input } from "../Input";
import { ReactComponent as Close } from "../../assets/close.svg";
import { ReactComponent as Tick } from "../../assets/checkMarkChip.svg";
import { Tooltip } from "../Tooltip";
export const HistoryPanel = ({
  historyPanelData = [],
  onClose,
  onSearchChange,
  onSelectConversation,
  onToggleGroup,
  openGroups,
  onMenuAction,
  activeConversationId,
}) => {
  // Normalize incoming data to support either:
  // 1) Array of groups (legacy)
  // 2) Object with { pinned: Conversation[], groups: Group[] }
  const baseGroups = useMemo(() => {
    if (Array.isArray(historyPanelData)) return historyPanelData;
    return historyPanelData?.groups || [];
  }, [historyPanelData]);
  const pinnedItems = useMemo(() => {
    // Support either explicit pinned list or per-item pinned boolean
    const fromObject = Array.isArray(historyPanelData?.pinned)
      ? historyPanelData.pinned
      : [];
    const fromGroups = (baseGroups || []).flatMap((g) =>
      (g?.conversation_list || []).filter((it) => !!it?.pinned)
    );
    return [...fromObject, ...fromGroups];
  }, [historyPanelData, baseGroups]);
  const groupsData = useMemo(() => {
    // Exclude pinned items from group lists if they are flagged as pinned
    return (baseGroups || []).map((g) => ({
      ...g,
      conversation_list: (g?.conversation_list || []).filter(
        (it) => !it?.pinned
      ),
    }));
  }, [baseGroups]);

  const [query, setQuery] = useState("");
  const [internalOpen, setInternalOpen] = useState({});
  const [focusedIndex, setFocusedIndex] = useState(-1);
  const containerRef = useRef(null);
  const [openMenuId, setOpenMenuId] = useState(null);
  const [editingId, setEditingId] = useState(null);
  const [tempName, setTempName] = useState("");
  const textRefs = useRef({});

  useEffect(() => {
    const init = {};
    (groupsData || []).forEach((g) => {
      if (g?.group_name) init[g.group_name] = true;
    });
    setInternalOpen((prev) => ({ ...init, ...prev }));
  }, [groupsData]);

  // Treat empty object as uncontrolled so groups default to open
  const isControlledGroups =
    openGroups !== undefined &&
    openGroups !== null &&
    Object.keys(openGroups).length > 0;
  const groupsState = useMemo(() => {
    if (!isControlledGroups) return internalOpen;
    const merged = {};
    (groupsData || []).forEach((g) => {
      const n = g?.group_name;
      if (!n) return;
      // Default missing controlled entries to true so other groups don't collapse
      merged[n] = openGroups?.[n] !== undefined ? openGroups[n] : true;
    });
    return merged;
  }, [isControlledGroups, openGroups, internalOpen, groupsData]);

  const handleSearch = (e) => {
    const value = e?.target?.value ?? "";
    setQuery(value);
    if (onSearchChange) onSearchChange(value);
  };

  const handleToggle = (name) => {
    const next = !groupsState?.[name];
    if (openGroups == null) {
      setInternalOpen((prev) => ({ ...prev, [name]: next }));
    }
    if (onToggleGroup) onToggleGroup(name, next);
  };

  const filtered = useMemo(() => {
    if (!query) return groupsData || [];
    const q = query.toLowerCase();
    return (groupsData || [])
      .map((g) => {
        const list = (g?.conversation_list || []).filter((c) => {
          const byName = c?.name?.toLowerCase?.().includes(q);
          const byModule = c?.module_name?.toLowerCase?.().includes(q);
          return byName || byModule;
        });
        return { ...g, conversation_list: list };
      })
      .filter((g) => (g?.conversation_list || []).length > 0);
  }, [groupsData, query]);

  const filteredPinned = useMemo(() => {
    if (!pinnedItems || pinnedItems.length === 0) return [];
    if (!query) return pinnedItems;
    const q = query.toLowerCase();
    return pinnedItems.filter((item) => {
      const byName = item?.name?.toLowerCase?.().includes(q);
      const byModule = item?.module_name?.toLowerCase?.().includes(q);
      return byName || byModule;
    });
  }, [pinnedItems, query]);

  // Flatten only visible items (from expanded groups) to align DOM order for keyboard nav
  const flatItems = useMemo(() => {
    const out = [];
    (filteredPinned || []).forEach((item) => {
      out.push({ groupName: "pinned", item });
    });
    (filtered || []).forEach((g) => {
      if (!groupsState?.[g?.group_name]) return;
      (g?.conversation_list || []).forEach((item) => {
        out.push({ groupName: g?.group_name, item });
      });
    });
    return out;
  }, [filtered, groupsState]);

  const currentFocused = flatItems[focusedIndex];

  useEffect(() => {
    const onDocClick = (e) => {
      if (!containerRef.current) return;
      // Keep menu open when clicking inside menu or on its trigger
      const isInsideMenu = e.target.closest(".history-item-menu");
      const isOnTrigger = e.target.closest(".item-menu-trigger");
      if (isInsideMenu || isOnTrigger) return;
      if (openMenuId != null) setOpenMenuId(null);
    };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, [openMenuId]);

  const focusItemAt = (idx) => {
    if (!containerRef.current) return;
    const nodes = containerRef.current.querySelectorAll(".history-item");
    const clamped = Math.max(0, Math.min(idx, nodes.length - 1));
    const el = nodes[clamped];
    if (el) {
      setFocusedIndex(clamped);
      // Defer focus to ensure React has applied tabIndex
      requestAnimationFrame(() => {
        el.focus();
      });
    }
  };

  const handleContainerKeyDown = (e) => {
    if (flatItems.length === 0) return;
    switch (e.key) {
      case "ArrowDown": {
        e.preventDefault();
        const next =
          focusedIndex < 0
            ? 0
            : Math.min(focusedIndex + 1, flatItems.length - 1);
        focusItemAt(next);
        break;
      }
      case "ArrowUp": {
        e.preventDefault();
        const prev = focusedIndex <= 0 ? 0 : focusedIndex - 1;
        focusItemAt(prev);
        break;
      }
      case "Home": {
        e.preventDefault();
        focusItemAt(0);
        break;
      }
      case "End": {
        e.preventDefault();
        focusItemAt(flatItems.length - 1);
        break;
      }
      case "Enter": {
        if (focusedIndex >= 0 && flatItems[focusedIndex]) {
          e.preventDefault();
          if (onSelectConversation)
            onSelectConversation(flatItems[focusedIndex].item);
        }
        break;
      }
      default:
        break;
    }
  };

  return (
    <div
      className="history-panel-container"
      ref={containerRef}
      onKeyDown={handleContainerKeyDown}
    >
      <div className="history-panel-header">
        <span>Your History</span>
        <img
          src={CloseIcon}
          alt="close"
          onClick={onClose}
          tabIndex={0}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              onClose();
            }
          }}
          role="button"
        />
      </div>
      <div className="history-panel-search">
        <input
          type="text"
          placeholder="Search by name or chat content"
          value={query}
          onChange={handleSearch}
          aria-label="Search history"
          onKeyDown={(e) => {
            if (e.key === "ArrowDown") {
              e.preventDefault();
              focusItemAt(0);
            }
          }}
        />
      </div>
      <div className="history-panel-groups">
        {filteredPinned && filteredPinned.length > 0 ? (
          <ul className="history-pinned-list">
            {filteredPinned.map((item, idx) =>
              editingId === item?.conversation_id ? (
                <Input
                  id=""
                  name=""
                  onChange={(e) => setTempName(e.target.value)}
                  rightIcon={
                    <div style={{ display: "flex", gap: "8px" }}>
                      <Close onClick={() => setEditingId(null)} />
                      <Tick
                        onClick={() => {
                          if (onMenuAction)
                            onMenuAction("rename", item, tempName);
                          setEditingId(null);
                        }}
                      />
                    </div>
                  }
                  type="text"
                  value={tempName}
                />
              ) : (
                <li
                  key={`pinned-${item?.conversation_id}-${idx}`}
                  className={`history-item history-pinned-item ${
                    activeConversationId === item?.conversation_id
                      ? "active"
                      : ""
                  }`}
                  role="button"
                  tabIndex={
                    currentFocused &&
                    currentFocused.groupName === "pinned" &&
                    currentFocused.item === item
                      ? 0
                      : -1
                  }
                  onClick={() =>
                    onSelectConversation && onSelectConversation(item)
                  }
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      if (onSelectConversation) onSelectConversation(item);
                    }
                  }}
                >
                  <div className="history-item-row">
                    <Tooltip
                      title={
                        textRefs.current[item.conversation_id]?.scrollWidth >
                        textRefs.current[item.conversation_id]?.clientWidth
                          ? item?.name
                          : ""
                      }
                      variant="tertiary"
                    >
                      <div
                        ref={(el) => {
                          if (el) textRefs.current[item.conversation_id] = el;
                        }}
                        className="history-item-name"
                      >
                        <span className="pin-icon" aria-hidden="true">
                          📌
                        </span>
                        {item?.name}
                      </div>
                    </Tooltip>

                    <button
                      type="button"
                      className={
                        "item-menu-trigger" +
                        (openMenuId === item?.conversation_id
                          ? " always-visible open"
                          : "")
                      }
                      aria-haspopup="menu"
                      aria-expanded={openMenuId === item?.conversation_id}
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenMenuId((prev) =>
                          prev === item?.conversation_id
                            ? null
                            : item?.conversation_id
                        );
                      }}
                      onKeyDown={(e) => {
                        e.stopPropagation();
                        if (e.key === "Enter" || e.key === " ") {
                          e.preventDefault();
                          setOpenMenuId((prev) =>
                            prev === item?.conversation_id
                              ? null
                              : item?.conversation_id
                          );
                        }
                      }}
                      title="More actions"
                    >
                      ⋯
                    </button>
                  </div>
                  {openMenuId === item?.conversation_id ? (
                    <div className="history-item-menu" role="menu">
                      <button
                        type="button"
                        className="menu-item"
                        role="menuitem"
                        onClick={(e) => {
                          e.stopPropagation();
                          if (onMenuAction) onMenuAction("share", item);
                          setOpenMenuId(null);
                        }}
                      >
                        Share
                      </button>
                      <button
                        type="button"
                        className="menu-item"
                        role="menuitem"
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenMenuId(null);
                          setEditingId(item?.conversation_id);
                          setTempName(item?.name);
                        }}
                      >
                        Rename
                      </button>
                      <button
                        type="button"
                        className="menu-item"
                        role="menuitem"
                        onClick={(e) => {
                          e.stopPropagation();
                          if (onMenuAction) onMenuAction("unpin", item);
                          setOpenMenuId(null);
                        }}
                      >
                        Unpin Chat
                      </button>
                      <button
                        type="button"
                        className="menu-item danger"
                        role="menuitem"
                        onClick={(e) => {
                          e.stopPropagation();
                          if (onMenuAction) onMenuAction("delete", item);
                          setOpenMenuId(null);
                        }}
                      >
                        Delete
                      </button>
                    </div>
                  ) : null}
                </li>
              )
            )}
          </ul>
        ) : null}
        {(filtered || []).map((group) => {
          const name = group?.group_name ?? "";
          const isOpen = !!groupsState?.[name];
          return (
            <div className="history-group" key={name}>
              <button
                className="history-group-header"
                type="button"
                onClick={() => handleToggle(name)}
                aria-expanded={isOpen}
              >
                <span className="chevron">{isOpen ? "▾" : "▸"}</span>
                <span className="group-title">{name}</span>
              </button>
              {isOpen && (
                <ul className="history-group-list">
                  {(group?.conversation_list || []).map((item, idx) =>
                    editingId === item?.conversation_id ? (
                      <Input
                        id=""
                        name=""
                        onChange={(e) => setTempName(e.target.value)}
                        rightIcon={
                          <div style={{ display: "flex", gap: "8px" }}>
                            <Close onClick={() => setEditingId(null)} />
                            <Tick
                              onClick={() => {
                                if (onMenuAction)
                                  onMenuAction("rename", item, tempName);
                                setEditingId(null);
                              }}
                            />
                          </div>
                        }
                        type="text"
                        value={tempName}
                      />
                    ) : (
                      <li
                        key={`${name}-${item?.conversation_id}-${idx}`}
                        className={`history-item ${
                          activeConversationId === item?.conversation_id
                            ? "active"
                            : ""
                        }`}
                        role="button"
                        tabIndex={
                          currentFocused &&
                          currentFocused.groupName === name &&
                          currentFocused.item === item
                            ? 0
                            : -1
                        }
                        onClick={() =>
                          onSelectConversation && onSelectConversation(item)
                        }
                        onKeyDown={(e) => {
                          if (e.key === "Enter" || e.key === " ") {
                            if (onSelectConversation)
                              onSelectConversation(item);
                          }
                        }}
                      >
                        <div className="history-item-row">
                          <Tooltip
                            title={
                              textRefs.current[item.conversation_id]
                                ?.scrollWidth >
                              textRefs.current[item.conversation_id]
                                ?.clientWidth
                                ? item?.name
                                : ""
                            }
                            variant="tertiary"
                          >
                            <div
                              ref={(el) => {
                                if (el)
                                  textRefs.current[item.conversation_id] = el;
                              }}
                              className="history-item-name"
                            >
                              {item?.name}
                            </div>
                          </Tooltip>
                          <button
                            type="button"
                            className={
                              "item-menu-trigger" +
                              (openMenuId === item?.conversation_id
                                ? " always-visible open"
                                : "")
                            }
                            aria-haspopup="menu"
                            aria-expanded={openMenuId === item?.conversation_id}
                            onClick={(e) => {
                              e.stopPropagation();
                              setOpenMenuId((prev) =>
                                prev === item?.conversation_id
                                  ? null
                                  : item?.conversation_id
                              );
                            }}
                            onKeyDown={(e) => {
                              // Prevent list keyboard handler from hijacking when using trigger
                              e.stopPropagation();
                              if (e.key === "Enter" || e.key === " ") {
                                e.preventDefault();
                                setOpenMenuId((prev) =>
                                  prev === item?.conversation_id
                                    ? null
                                    : item?.conversation_id
                                );
                              }
                            }}
                            title="More actions"
                          >
                            ⋯
                          </button>
                        </div>
                        {openMenuId === item?.conversation_id ? (
                          <div className="history-item-menu" role="menu">
                            <button
                              type="button"
                              className="menu-item"
                              role="menuitem"
                              onClick={(e) => {
                                e.stopPropagation();
                                if (onMenuAction) onMenuAction("share", item);
                                setOpenMenuId(null);
                              }}
                            >
                              Share
                            </button>
                            <button
                              type="button"
                              className="menu-item"
                              role="menuitem"
                              onClick={(e) => {
                                e.stopPropagation();
                                setOpenMenuId(null);
                                setEditingId(item?.conversation_id);
                                setTempName(item?.name);
                              }}
                            >
                              Rename
                            </button>
                            <button
                              type="button"
                              className="menu-item"
                              role="menuitem"
                              onClick={(e) => {
                                e.stopPropagation();
                                if (onMenuAction) onMenuAction("pin", item);
                                setOpenMenuId(null);
                              }}
                            >
                              Pin Chat
                            </button>
                            <button
                              type="button"
                              className="menu-item danger"
                              role="menuitem"
                              onClick={(e) => {
                                e.stopPropagation();
                                if (onMenuAction) onMenuAction("delete", item);
                                setOpenMenuId(null);
                              }}
                            >
                              Delete
                            </button>
                          </div>
                        ) : null}
                      </li>
                    )
                  )}
                </ul>
              )}
            </div>
          );
        })}
        {filtered.length === 0 ? (
          <div className="history-empty-state">No conversations found</div>
        ) : null}
      </div>
    </div>
  );
};
