import { isMobileOrTablet } from '@rpg-engine/shared';
import React from 'react';
import styled from 'styled-components';
import { Dropdown, IOptionsProps } from '../../Dropdown';
import { SearchBar } from '../SearchBar/SearchBar';

interface ISearchHeaderProps {
  searchOptions?: {
    value: string;
    onChange: (value: string) => void;
    placeholder?: string;
    rightElement?: React.ReactNode;
  };
  filterOptions?: {
    options: IOptionsProps[];
    selectedOption: string;
    onOptionChange: (value: string) => void;
  };
  className?: string;
}

export const SearchHeader: React.FC<ISearchHeaderProps> = ({
  searchOptions,
  filterOptions,
  className,
}) => {
  if (!searchOptions && !filterOptions) return null;

  const isMobile = isMobileOrTablet();
  const isSmallScreen = isMobile && window.innerWidth < 480;

  return (
    <HeaderContainer className={className}>
      <HeaderContent $isSmallScreen={isSmallScreen}>
        {searchOptions && (
          <SearchContainer>
            <StyledSearchBar
              value={searchOptions.value}
              onChange={searchOptions.onChange}
              placeholder={
                isSmallScreen
                  ? 'Search...'
                  : searchOptions.placeholder || 'Search...'
              }
              rightElement={searchOptions.rightElement}
            />
          </SearchContainer>
        )}
        {filterOptions && (
          <FilterContainer $isSmallScreen={isSmallScreen}>
            <StyledDropdown
              options={filterOptions.options}
              onChange={filterOptions.onOptionChange}
              width={isSmallScreen ? '100%' : '200px'}
            />
          </FilterContainer>
        )}
      </HeaderContent>
    </HeaderContainer>
  );
};

const HeaderContainer = styled.div``;

const HeaderContent = styled.div<{ $isSmallScreen?: boolean }>`
  display: flex;
  flex-direction: ${props => (props.$isSmallScreen ? 'column' : 'row')};
  justify-content: space-between;
  align-items: ${props => (props.$isSmallScreen ? 'stretch' : 'center')};
  gap: ${props => (props.$isSmallScreen ? '0.5rem' : '1rem')};
  background: rgba(0, 0, 0, 0.2);
  padding: ${props => (props.$isSmallScreen ? '0.5rem' : '1rem')};
  border-radius: 4px;
`;

const SearchContainer = styled.div`
  flex: 1;
`;

const FilterContainer = styled.div<{ $isSmallScreen?: boolean }>`
  display: flex;
  justify-content: ${props => (props.$isSmallScreen ? 'stretch' : 'flex-end')};
  width: ${props => (props.$isSmallScreen ? '100%' : 'auto')};
`;

const StyledSearchBar = styled(SearchBar)`
  width: 100%;
`;

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