import {
  IInformationCenterItem,
  IInformationCenterNPC,
  isMobileOrTablet,
} from '@rpg-engine/shared';
import React, { useMemo, useState } from 'react';
import styled from 'styled-components';
import { useTooltipPosition } from '../../../../hooks/useTooltipPosition';
import { PaginatedContent } from '../../../shared/PaginatedContent/PaginatedContent';
import { Portal } from '../../../shared/Portal/Portal';
import { InformationCenterCell } from '../../InformationCenterCell';
import { BaseInformationDetails } from '../../shared/BaseInformationDetails';
import { InformationCenterItemDetails } from './InformationCenterItemDetails';
import { InformationCenterItemTooltip } from './InformationCenterItemTooltip';
import { ItemsAdvancedFilters } from './ItemsAdvancedFilters';

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 [selectedTier, setSelectedTier] = useState<string>('all');
  const [isAdvancedFiltersOpen, setIsAdvancedFiltersOpen] = useState(false);
  const [
    selectedItem,
    setSelectedItem,
  ] = useState<IInformationCenterItem | null>(null);

  const {
    tooltipState,
    handleMouseEnter,
    handleMouseLeave,
    TOOLTIP_WIDTH,
  } = useTooltipPosition<IInformationCenterItem>();

  const filteredItems = useMemo<IInformationCenterItem[]>(() => {
    return items.filter(item => {
      const matchesSearch = item.name
        .toLowerCase()
        .includes(searchQuery.toLowerCase());
      const matchesCategory =
        selectedItemCategory === 'all' || item.type === selectedItemCategory;
      const matchesTier =
        selectedTier === 'all' || String(item.tier) === selectedTier;

      return matchesSearch && matchesCategory && matchesTier;
    });
  }, [items, searchQuery, selectedItemCategory, selectedTier]);

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

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

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

  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(item, e)}
      onMouseLeave={handleMouseLeave}
      onTouchStart={e => handleTouchStart(e, item)}
      onClick={() => handleItemClick(item)}
    />
  );

  const SearchBarRightElement = (
    <SearchBarActions>
      <ItemsAdvancedFilters
        isOpen={isAdvancedFiltersOpen}
        onToggle={() => setIsAdvancedFiltersOpen(!isAdvancedFiltersOpen)}
        onTierChange={setSelectedTier}
        onTypeChange={setSelectedItemCategory}
        selectedTier={selectedTier}
        selectedType={selectedItemCategory}
      />
    </SearchBarActions>
  );

  return (
    <>
      <PaginatedContent<IInformationCenterItem>
        items={filteredItems}
        renderItem={renderItem}
        emptyMessage="No items found"
        searchOptions={{
          value: searchQuery,
          onChange: handleSearchChange,
          placeholder: 'Search items...',
          rightElement: SearchBarRightElement,
        }}
        dependencies={[selectedItemCategory, selectedTier]}
        tabId={tabId}
        layout="grid"
        itemHeight={isMobile ? '150px' : '180px'}
      />
      {!isMobile && tooltipState && tooltipState.item && (
        <Portal>
          <TooltipWrapper
            width={TOOLTIP_WIDTH}
            style={{
              position: 'fixed',
              left: `${tooltipState.position.x}px`,
              top: `${tooltipState.position.y}px`,
            }}
          >
            <InformationCenterItemTooltip item={tooltipState.item} />
          </TooltipWrapper>
        </Portal>
      )}
      {selectedItem && (
        <Portal>
          <BaseInformationDetails
            name={selectedItem.name}
            spriteKey={selectedItem.texturePath}
            atlasJSON={itemsAtlasJSON}
            atlasIMG={itemsAtlasIMG}
            onBack={() => setSelectedItem(null)}
          >
            <InformationCenterItemDetails
              item={selectedItem}
              itemsAtlasJSON={itemsAtlasJSON}
              itemsAtlasIMG={itemsAtlasIMG}
              droppedBy={getDroppedByNPCs(selectedItem.key, bestiaryItems)}
              onBack={() => setSelectedItem(null)}
            />
          </BaseInformationDetails>
        </Portal>
      )}
    </>
  );
};

const TooltipWrapper = styled.div<{ width: number }>`
  z-index: 1000;
  pointer-events: none;
  width: ${props => `${props.width}px`};
`;

const SearchBarActions = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;
