import {
  IInformationCenterNPC,
  isMobileOrTablet,
  MovementSpeed,
  RangeTypes,
} from '@rpg-engine/shared';
import React, { useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../../../constants/uiColors';
import { Collapsible } from '../../../shared/Collapsible/Collapsible';
import { Pagination } from '../../../shared/Pagination/Pagination';
import { SearchBar } from '../../../shared/SearchBar/SearchBar';
import { SpriteFromAtlas } from '../../../shared/SpriteFromAtlas';

import { BaseInformationDetails } from '../../shared/BaseInformationDetails';

interface INPCDetailsProps {
  npc: IInformationCenterNPC;
  itemsAtlasJSON: Record<string, any>;
  itemsAtlasIMG: string;
  entitiesAtlasJSON: Record<string, any>;
  entitiesAtlasIMG: string;
  iconAtlasIMG?: any;
  iconAtlasJSON?: any;
  onBack: () => void;
}

const ITEMS_PER_PAGE = 5;

export const formatItemName = (itemPath: string): string => {
  const cleanText =
    itemPath
      .split('/')
      .pop()
      ?.split('.')
      .shift() || '';

  return cleanText
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

export const InformationCenterNPCDetails: React.FC<INPCDetailsProps> = ({
  npc,
  itemsAtlasJSON,
  itemsAtlasIMG,
  entitiesAtlasJSON,
  entitiesAtlasIMG,
  iconAtlasIMG,
  iconAtlasJSON,
  onBack,
}) => {
  const isMobile = isMobileOrTablet();
  const [lootSearchQuery, setLootSearchQuery] = useState('');
  const [currentLootPage, setCurrentLootPage] = useState(1);

  const formatText = (text: string | RangeTypes | MovementSpeed): string => {
    if (typeof text === 'number') {
      return text.toString();
    }

    return text
      .toString()
      .replace(/([A-Z])/g, ' $1')
      .trim()
      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
      .replace(/\s+/g, ' ')
      .replace(/^\w/, c => c.toUpperCase());
  };

  const formatRarity = (rarity: number): string => {
    switch (rarity) {
      case 0.5:
        return 'Very Rare';
      case 1:
        return 'Rare';
      case 10:
        return 'Uncommon';
      case 15:
        return 'Semi Common';
      case 20:
        return 'Common';
      case 35:
        return 'Very Common';
      default:
        return 'Unknown';
    }
  };

  const filteredLoots =
    npc.loots?.filter(loot =>
      formatItemName(loot.itemBlueprintKey)
        .toLowerCase()
        .includes(lootSearchQuery.toLowerCase())
    ) || [];

  const totalLootPages = Math.ceil(filteredLoots.length / ITEMS_PER_PAGE);
  const paginatedLoots = filteredLoots.slice(
    (currentLootPage - 1) * ITEMS_PER_PAGE,
    currentLootPage * ITEMS_PER_PAGE
  );

  return (
    <BaseInformationDetails
      name={npc.name}
      spriteKey={npc.key}
      atlasJSON={entitiesAtlasJSON}
      atlasIMG={entitiesAtlasIMG}
      onBack={onBack}
    >
      <InfoSection>
        <InfoItem>
          <Label>Type:</Label>
          <Value>{formatText(npc.subType)}</Value>
        </InfoItem>
        <InfoItem>
          <Label>Alignment:</Label>
          <Value>{formatText(npc.alignment)}</Value>
        </InfoItem>
        <InfoItem>
          <Label>Attack Type:</Label>
          <Value>{formatText(npc.attackType)}</Value>
        </InfoItem>
        <InfoItem>
          <Label>Range:</Label>
          <Value>{formatText(npc.maxRangeAttack)}</Value>
        </InfoItem>
        <InfoItem>
          <Label>Speed:</Label>
          <Value>{formatText(npc.speed)}</Value>
        </InfoItem>
      </InfoSection>

      <StyledCollapsible title="Stats" defaultOpen={!isMobile}>
        <StatGrid>
          <StatItem>HP: {npc.baseHealth}</StatItem>
          <StatItem>Level: {npc.skills.level}</StatItem>
          {npc.skills.strength?.level && (
            <StatItem>Strength: {npc.skills.strength.level}</StatItem>
          )}
          {npc.skills.dexterity?.level && (
            <StatItem>Dexterity: {npc.skills.dexterity.level}</StatItem>
          )}
          {npc.skills.resistance?.level && (
            <StatItem>Resistance: {npc.skills.resistance.level}</StatItem>
          )}
        </StatGrid>
      </StyledCollapsible>

      {npc.loots && npc.loots.length > 0 && (
        <StyledCollapsible title="Loot" defaultOpen={!isMobile}>
          <LootSearchContainer>
            <StyledSearchBar
              value={lootSearchQuery}
              onChange={setLootSearchQuery}
              placeholder="Search loot..."
            />
          </LootSearchContainer>
          <LootGrid>
            {paginatedLoots.map((loot, index) => (
              <LootItem key={index}>
                <SpriteFromAtlas
                  atlasJSON={itemsAtlasJSON}
                  atlasIMG={itemsAtlasIMG}
                  spriteKey={loot.itemBlueprintKey}
                  width={24}
                  height={24}
                  imgScale={1}
                />
                <LootDetails>
                  <LootName>{formatItemName(loot.itemBlueprintKey)}</LootName>
                  <LootInfo>
                    <LootChance>{formatRarity(loot.chance)}</LootChance>
                    {loot.quantityRange && (
                      <LootQuantity>
                        x{loot.quantityRange[0]}-{loot.quantityRange[1]}
                      </LootQuantity>
                    )}
                  </LootInfo>
                </LootDetails>
              </LootItem>
            ))}
          </LootGrid>
          {filteredLoots.length > ITEMS_PER_PAGE && (
            <PaginationContainer>
              <StyledPagination
                currentPage={currentLootPage}
                totalPages={totalLootPages}
                onPageChange={setCurrentLootPage}
              />
            </PaginationContainer>
          )}
        </StyledCollapsible>
      )}

      {npc.entityEffects && npc.entityEffects.length > 0 && (
        <StyledCollapsible title="Effects" defaultOpen={!isMobile}>
          <EffectsList>
            {npc.entityEffects.map((effect, index) => (
              <EffectItem key={index}>{formatText(effect)}</EffectItem>
            ))}
          </EffectsList>
        </StyledCollapsible>
      )}

      {npc.areaSpells && npc.areaSpells.length > 0 && (
        <StyledCollapsible title="Spells" defaultOpen={!isMobile}>
          <SpellsList>
            {npc.areaSpells.map((spell, index) => (
              <SpellItem key={index}>
                <SpellIconContainer>
                  <SpriteFromAtlas
                    atlasJSON={iconAtlasJSON}
                    atlasIMG={iconAtlasIMG}
                    spriteKey={spell.texturePath || spell.spellKey}
                    width={24}
                    height={24}
                    imgScale={1}
                  />
                </SpellIconContainer>
                <SpellContent>
                  <SpellName>{formatText(spell.spellKey)}</SpellName>
                  <SpellDetails>
                    Power: <SpellValue>{formatText(spell.power)}</SpellValue>
                    <Separator>•</Separator>
                    Chance: <SpellValue>{spell.probability}%</SpellValue>
                  </SpellDetails>
                </SpellContent>
              </SpellItem>
            ))}
          </SpellsList>
        </StyledCollapsible>
      )}
    </BaseInformationDetails>
  );
};

const InfoSection = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
  background: rgba(255, 255, 255, 0.05);
  padding: 12px;
  border-radius: 4px;
`;

const InfoItem = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
`;

const Label = styled.span`
  color: ${uiColors.yellow};
  font-size: 0.5rem;
  opacity: 0.8;
`;

const Value = styled.span`
  color: ${uiColors.white};
  font-size: 0.5rem;
`;

const StyledCollapsible = styled(Collapsible)`
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
  overflow: visible;
  scrollbar-width: thin;
  scrollbar-color: ${uiColors.darkGray} transparent;
  width: 100%;
  box-sizing: border-box;
`;

const StatGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 8px;
  padding: 12px;
`;

const StatItem = styled.div`
  color: ${uiColors.white};
  font-size: 0.5rem;
  background: rgba(255, 255, 255, 0.05);
  padding: 8px;
  border-radius: 4px;
`;

const EffectsList = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px;
`;

const EffectItem = styled.div`
  color: ${uiColors.white};
  font-size: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
`;

const SpellsList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
`;

const SpellIconContainer = styled.div`
  display: flex;
  padding-right: 30px;
  padding-bottom: 30px;
`;

const SpellContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
`;

const SpellItem = styled.div`
  display: flex;
  gap: 8px;
  background: rgba(255, 255, 255, 0.05);
  padding: 8px;
  padding-left: 10px;
  border-radius: 4px;
  align-items: center;
`;

const SpellName = styled.div`
  color: ${uiColors.yellow};
  font-size: 0.5rem;
`;

const SpellDetails = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  color: ${uiColors.white};
  font-size: 0.45rem;
  opacity: 0.8;
`;

const SpellValue = styled.span`
  color: ${uiColors.yellow};
`;

const Separator = styled.span`
  color: ${uiColors.yellow};
  opacity: 0.5;
`;

const LootSearchContainer = styled.div`
  padding: 8px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  margin: 8px 8px 4px;
  box-sizing: border-box;
`;

const StyledSearchBar = styled(SearchBar)`
  width: 100%;
  box-sizing: border-box;
  input {
    background: rgba(0, 0, 0, 0.2) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    box-sizing: border-box;
    &:focus {
      border-color: ${uiColors.yellow} !important;
    }
  }
`;

const LootGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 4px;
  padding: 4px 8px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    padding: 4px;
  }
`;

const LootItem = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  background: rgba(255, 255, 255, 0.05);
  padding: 4px;
  border-radius: 4px;
  min-width: 0;
`;

const LootDetails = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
`;

const LootName = styled.div`
  color: ${uiColors.white};
  font-size: 0.5rem;
`;

const LootInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
`;

const LootChance = styled.span`
  color: ${uiColors.yellow};
  font-size: 0.45rem;
`;

const LootQuantity = styled.span`
  color: ${uiColors.lightGray};
  font-size: 0.45rem;
`;

const PaginationContainer = styled.div`
  display: flex;
  justify-content: center;
  padding: 12px;
`;

const StyledPagination = styled(Pagination)`
  font-size: 0.6rem;
`;
