import React from 'react';
import styled from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Spinner } from '@/shared/components/ui';
import type { SearchSuggestion } from '@/features/search/types/search.types';

const Wrap = styled.div`
  margin-bottom: ${({ theme }) => theme.spacing[4]};
`;

const Title = styled.h2`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.secondary};
  margin: 0 0 ${({ theme }) => theme.spacing[2]};
  text-align: start;
`;

const Chips = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const Chip = styled.button`
  border: 1px solid ${({ theme }) => theme.colors.border};
  background: ${({ theme }) => theme.colors.surface};
  color: ${({ theme }) => theme.colors.text.primary};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  padding: ${({ theme }) => `${theme.spacing[1]} ${theme.spacing[3]}`};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  cursor: pointer;

  &:hover {
    border-color: ${({ theme }) => theme.colors.primary};
    color: ${({ theme }) => theme.colors.primary};
  }
`;

const Message = styled.div`
  margin: 0;
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-align: start;
`;

interface SearchSuggestionsListProps {
  suggestions: SearchSuggestion[];
  isLoading?: boolean;
  isError?: boolean;
  onSelect: (query: string) => void;
}

export const SearchSuggestionsList: React.FC<SearchSuggestionsListProps> = ({
  suggestions,
  isLoading,
  isError,
  onSelect,
}) => {
  const { t } = useLocale();

  if (isLoading) {
    return (
      <Wrap>
        <Message role="status">
          <Spinner size="sm" /> {t('search:suggestions.loading')}
        </Message>
      </Wrap>
    );
  }

  if (isError) {
    return (
      <Wrap>
        <Message role="alert">{t('search:suggestions.error')}</Message>
      </Wrap>
    );
  }

  if (suggestions.length === 0) {
    return null;
  }

  return (
    <Wrap>
      <Title>{t('search:suggestions.title')}</Title>
      <Chips>
        {suggestions.map((item) => (
          <Chip
            key={`${item.search_query}-${item.created_at ?? ''}`}
            type="button"
            onClick={() => onSelect(item.search_query)}
          >
            {item.search_query}
          </Chip>
        ))}
      </Chips>
    </Wrap>
  );
};
