import React from 'react';
import styled from 'styled-components';
import { usePagination } from '../CraftBook/hooks/usePagination';
import { Dropdown, IOptionsProps } from '../Dropdown';
import { Pagination } from '../shared/Pagination/Pagination';
import { SearchBar } from '../shared/SearchBar/SearchBar';

interface IInformationCenterTabViewProps<T> {
  items: T[];
  searchQuery: string;
  onSearchChange: (query: string) => void;
  filterItems: (items: T[]) => T[];
  renderContent: (items: T[]) => React.ReactNode;
  searchPlaceholder: string;
  filterOptions?: {
    options: IOptionsProps[];
    selectedOption: string;
    onOptionChange: (value: string) => void;
  };
  emptyMessage?: string;
  dependencies?: any[];
}

const ITEMS_PER_PAGE = 5;

export function InformationCenterTabView<T>({
  items,
  searchQuery,
  onSearchChange,
  filterItems,
  renderContent,
  searchPlaceholder,
  filterOptions,
  emptyMessage = 'No items found',
  dependencies = [],
}: IInformationCenterTabViewProps<T>): React.ReactElement {
  const filteredItems = filterItems(items);

  const {
    currentPage,
    setCurrentPage,
    paginatedItems,
    totalPages,
  } = usePagination({
    items: filteredItems,
    itemsPerPage: ITEMS_PER_PAGE,
    dependencies: [searchQuery, ...dependencies],
  });

  return (
    <Section>
      <HeaderContainer>
        <StyledSearchBar
          value={searchQuery}
          onChange={onSearchChange}
          placeholder={searchPlaceholder}
        />
        {filterOptions && (
          <StyledDropdown
            options={filterOptions.options}
            onChange={filterOptions.onOptionChange}
            width="200px"
          />
        )}
      </HeaderContainer>

      {paginatedItems.length === 0 ? (
        <EmptyMessage>{emptyMessage}</EmptyMessage>
      ) : (
        <>
          {renderContent(paginatedItems)}
          <StyledPagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
          />
        </>
      )}
    </Section>
  );
}

const Section = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1rem;
  height: 100%;
  min-height: 400px;
  overflow-y: auto;
`;

const HeaderContainer = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
  margin-top: 1.5rem;
`;

const StyledSearchBar = styled(SearchBar)`
  margin-bottom: 1rem;
`;

const StyledDropdown = styled(Dropdown)`
  min-width: 150px;
`;

const StyledPagination = styled(Pagination)`
  margin-top: 1rem;
`;

const EmptyMessage = styled.div`
  text-align: center;
  color: #9ca3af;
  padding: 2rem;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
`;
