import { IFaqItem } from '@rpg-engine/shared';
import React, { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { Collapsible } from '../../../shared/Collapsible/Collapsible';
import { PaginatedContent } from '../../../shared/PaginatedContent/PaginatedContent';
import { SearchHeader } from '../../../shared/SearchHeader/SearchHeader';

interface IFaqSectionProps {
  faqItems: IFaqItem[];
  initialSearchQuery: string;
  tabId: string;
}

export const InformationCenterFAQSection: React.FC<IFaqSectionProps> = ({
  faqItems,
  initialSearchQuery,
  tabId,
}) => {
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery);

  useEffect(() => {
    setSearchQuery(initialSearchQuery);
  }, [initialSearchQuery]);

  const filteredFaqs = useMemo(() => {
    if (!searchQuery) return faqItems;
    return faqItems.filter(
      faq =>
        faq.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
        faq.answer.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [searchQuery, faqItems]);

  const renderItem = (item: IFaqItem) => (
    <StyledCollapsible title={item.question}>
      <Answer>{item.answer}</Answer>
    </StyledCollapsible>
  );

  return (
    <Container>
      <SearchHeader
        searchOptions={{
          value: searchQuery,
          onChange: setSearchQuery,
          placeholder: 'Search FAQs...',
        }}
      />
      <PaginatedContent<IFaqItem>
        items={filteredFaqs}
        renderItem={renderItem}
        emptyMessage="No FAQ items found"
        tabId={tabId}
        layout="list"
        itemsPerPage={10}
      />
    </Container>
  );
};

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 100%;
`;

const StyledCollapsible = styled(Collapsible)`
  margin-bottom: 0.5rem;

  &:last-child {
    margin-bottom: 0;
  }
`;

const Answer = styled.p`
  font-size: 0.9rem;
  color: #ffffff;
  margin: 0;
  line-height: 1.5;
`;
