import { debounce } from 'lodash';
import React, { useCallback, useState } from 'react';
import styled from 'styled-components';
import { InternalTabs, UserActionLink } from '../..';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import { IFriend } from './FriendList';

interface ISearchFriendProps {
  searchedCharacters: IFriend[];
  friendRequests: IFriend[];
  onFocus?: () => void;
  onBlur?: () => void;
  onSearch: (characterName: string) => void;
  onSendFriendRequest: (character: IFriend) => void;
  onAcceptRequest: (character: IFriend) => void;
  onRejectRequest: (character: IFriend) => void;
}

export const SearchFriend: React.FC<ISearchFriendProps> = ({
  searchedCharacters,
  friendRequests,
  onBlur,
  onFocus,
  onSearch,
  onSendFriendRequest,
  onAcceptRequest,
  onRejectRequest,
}) => {
  const [characterName, setCharacterName] = useState('');

  const debouncedSearch = useCallback(
    debounce((name: string) => {
      onSearch(name);
    }, 300),
    []
  );

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.value;
    setCharacterName(name);
    debouncedSearch(name);
  };

  const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (characterName.trim()) {
      onSearch(characterName);
    }
  };

  const searchTabContent = (
    <ListContainer>
      <SearchForm onSubmit={handleSubmit}>
        <SearchInput
          value={characterName}
          id="characterName"
          name="characterName"
          onChange={handleInputChange}
          type="text"
          autoComplete="off"
          onFocus={onFocus}
          onBlur={onBlur}
          onPointerDown={onFocus}
          autoFocus
          placeholder="Search for a character..."
        />
      </SearchForm>
      <CharacterList
        characters={searchedCharacters}
        onAction={onSendFriendRequest}
        actionLabel="Add Friend"
      />
    </ListContainer>
  );

  const requestsTabContent = (
    <ListContainer>
      <FriendRequestSection
        friendRequests={friendRequests}
        onAccept={onAcceptRequest}
        onReject={onRejectRequest}
      />
    </ListContainer>
  );

  const tabs = [
    { id: 'search', title: 'Search', content: searchTabContent },
    {
      id: 'requests',
      title: `Requests (${friendRequests.length})`,
      content: requestsTabContent,
    },
  ];

  return (
    <Container>
      <InternalTabs
        tabs={tabs}
        activeTextColor="#000"
        inactiveColor="#777"
        borderColor="#f59e0b"
      />
    </Container>
  );
};

const CharacterList: React.FC<{
  characters: IFriend[];
  onAction: (character: IFriend) => void;
  actionLabel: string;
}> = ({ characters, onAction, actionLabel }) => (
  <ListContainer>
    {characters.map(character => (
      <ListItem key={character._id}>
        <CharacterName>{character.name}</CharacterName>
        <UserActionLink
          color={uiColors.lightGreen}
          onClick={() => onAction(character)}
        >
          {actionLabel}
        </UserActionLink>
      </ListItem>
    ))}
  </ListContainer>
);

const FriendRequestSection: React.FC<{
  friendRequests: IFriend[];
  onAccept: (character: IFriend) => void;
  onReject: (character: IFriend) => void;
}> = ({ friendRequests, onAccept, onReject }) => (
  <>
    {friendRequests.length > 0 && (
      <ListContainer>
        {friendRequests.map(character => (
          <ListItem key={character._id}>
            <CharacterName>{character.name}</CharacterName>
            <AcceptRejectActions>
              <UserActionLink
                color={uiColors.lightGreen}
                onClick={() => onAccept(character)}
              >
                Accept
              </UserActionLink>
              <UserActionLink
                color={uiColors.red}
                onClick={() => onReject(character)}
              >
                Reject
              </UserActionLink>
            </AcceptRejectActions>
          </ListItem>
        ))}
      </ListContainer>
    )}
  </>
);

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

const SearchForm = styled.form`
  display: flex;
  align-items: center;
  width: 100%;
  margin-top: 1rem;
`;

const SearchInput = styled.input`
  width: 100%;
  background-color: rgba(0, 0, 0, 0.25);
  border: none;
  padding: 0.5rem;
  font-size: ${uiFonts.size.small};
`;

const ListContainer = styled.ul`
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
  max-height: 50vh;
  overflow-y: auto;

  @media (max-width: 768px) {
    max-height: 90vh;
  }
`;

const ListItem = styled.li`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;

const CharacterName = styled.p`
  font-size: ${uiFonts.size.small};
  margin: 0;
`;

const AcceptRejectActions = styled.div`
  display: flex;
  gap: 0.5rem;
`;
