import {
  IInformationCenterItem,
  IInformationCenterNPC,
  ItemType,
  isMobileOrTablet,
} from '@rpg-engine/shared';
import React, { useState } from 'react';
import styled from 'styled-components';
import { IOptionsProps } from '../../../Dropdown';
import { PaginatedContent } from '../../../shared/PaginatedContent/PaginatedContent';
import { Portal } from '../../../shared/Portal/Portal';
import { InformationCenterCell } from '../../InformationCenterCell';
import { InformationCenterItemDetails } from './InformationCenterItemDetails';
import { InformationCenterItemTooltip } from './InformationCenterItemTooltip';

const TOOLTIP_OFFSET = 200;

interface IItemsSectionProps {
  items: IInformationCenterItem[];
  bestiaryItems: IInformationCenterNPC[];
  itemsAtlasJSON: Record<string, any>;
  itemsAtlasIMG: string;
  initialSearchQuery: string;
  tabId: string;
}

export const formatItemType = (type: string): string => {
  const words = type.split(/(?=[A-Z])/);

  if (words.length === 1) {
    return words[0];
  }

  return words
    .map((word, index) => {
      if (index === 0) {
        return word.charAt(0) + '.';
      }
      return word;
    })
    .join(' ');
};

export const InformationCenterItemsSection: React.FC<IItemsSectionProps> = ({
  items,
  bestiaryItems,
  itemsAtlasJSON,
  itemsAtlasIMG,
  initialSearchQuery,
  tabId,
}) => {
  const isMobile = isMobileOrTablet();
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery);
  const [selectedItemCategory, setSelectedItemCategory] = useState<string>(
    'all'
  );
  const [hoveredItem, setHoveredItem] = useState<IInformationCenterItem | null>(
    null
  );
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
  const [
    selectedItem,
    setSelectedItem,
  ] = useState<IInformationCenterItem | null>(null);

  const itemCategoryOptions: IOptionsProps[] = [
    { id: 0, value: 'all', option: 'All Items' },
    ...Object.values(ItemType).map((type, index) => ({
      id: index + 1,
      value: type,
      option: formatItemType(type),
    })),
  ];

  const filteredItems = items.filter(
    item =>
      (selectedItemCategory === 'all' || item.type === selectedItemCategory) &&
      item.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getDroppedByNPCs = (
    itemId: string,
    npcs: IInformationCenterNPC[]
  ): IInformationCenterNPC[] => {
    return (
      npcs.filter(npc =>
        npc.loots?.some(loot => loot.itemBlueprintKey === itemId)
      ) || []
    );
  };

  const handleMouseEnter = (
    e: React.MouseEvent,
    item: IInformationCenterItem
  ) => {
    if (!isMobile) {
      setTooltipPosition({
        x: e.clientX + TOOLTIP_OFFSET,
        y: e.clientY,
      });
      setHoveredItem(item);
    }
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isMobile && hoveredItem) {
      setTooltipPosition({
        x: e.clientX + TOOLTIP_OFFSET,
        y: e.clientY,
      });
    }
  };

  const handleMouseLeave = () => {
    if (!isMobile) {
      setHoveredItem(null);
    }
  };

  const handleTouchStart = (
    e: React.TouchEvent,
    item: IInformationCenterItem
  ) => {
    e.preventDefault();
    setSelectedItem(item);
  };

  const handleItemClick = (item: IInformationCenterItem) => {
    setSelectedItem(item);
    setHoveredItem(null);
  };

  const handleSearchChange = (newQuery: string) => {
    setSearchQuery(newQuery);
    if (newQuery && selectedItemCategory !== 'all') {
      setSelectedItemCategory('all');
    }
  };

  const renderItem = (item: IInformationCenterItem) => (
    <InformationCenterCell
      key={item.key}
      name={item.name}
      spriteKey={item.texturePath}
      atlasJSON={itemsAtlasJSON}
      atlasIMG={itemsAtlasIMG}
      onMouseEnter={e => handleMouseEnter(e, item)}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      onTouchStart={e => handleTouchStart(e, item)}
      onClick={() => handleItemClick(item)}
    />
  );

  return (
    <>
      <PaginatedContent<IInformationCenterItem>
        items={filteredItems}
        renderItem={renderItem}
        emptyMessage="No items found"
        filterOptions={{
          options: itemCategoryOptions,
          selectedOption: selectedItemCategory,
          onOptionChange: setSelectedItemCategory,
        }}
        searchOptions={{
          value: searchQuery,
          onChange: handleSearchChange,
          placeholder: 'Search items...',
        }}
        dependencies={[selectedItemCategory]}
        tabId={tabId}
        layout="grid"
        itemHeight="180px"
      />
      {!isMobile && hoveredItem && (
        <TooltipWrapper
          style={{ top: tooltipPosition.y, left: tooltipPosition.x }}
        >
          <InformationCenterItemTooltip item={hoveredItem} />
        </TooltipWrapper>
      )}
      {selectedItem && (
        <Portal>
          <InformationCenterItemDetails
            item={selectedItem}
            itemsAtlasJSON={itemsAtlasJSON}
            itemsAtlasIMG={itemsAtlasIMG}
            droppedBy={getDroppedByNPCs(selectedItem.key, bestiaryItems)}
            onBack={() => setSelectedItem(null)}
          />
        </Portal>
      )}
    </>
  );
};

const TooltipWrapper = styled.div`
  position: fixed;
  z-index: 1000;
  pointer-events: none;
  transition: transform 0.1s ease;
`;
