import { Avatar } from 'components/avatar';
import { Card } from 'components/card';
import { ActivityIndicator, Col, Row, TouchableHighlight } from 'components/layout';
import { Text } from 'components/text';
import { TextField } from 'components/text-field';
import { useResponsiveLayout } from 'hooks';
import { SearchIcon } from 'icons';
import { FC, useCallback, useEffect, useRef, useState } from 'react';
import { useFastSearchUsersByStringQuery } from 'expo-schema';

const WAIT_TO_SEARCH = 500;
export const Invite: FC<InviteType> = ({ participantId, setParticipantId }) => {
  const delayDebounceRef = useRef<any>(null);
  const [queryString, setQueryString] = useState('');
  const { data, refetch, loading } = useFastSearchUsersByStringQuery({
    fetchPolicy: 'network-only',
    variables: {
      input: {
        queryString: '',
      },
    },
  });
  const { isMobile } = useResponsiveLayout();
  const outerHeight = isMobile ? undefined : 300;
  const maxHeight = isMobile ? undefined : 280;

  useEffect(() => {
    delayDebounceRef.current = setTimeout(() => {
      const isSearchable = queryString.length > 1;
      if (isSearchable) {
        refetch({
          input: {
            queryString,
          },
        });
      }
    }, WAIT_TO_SEARCH);
    return () => clearTimeout(delayDebounceRef.current);
  }, [queryString, refetch]);

  const users = data?.fastSearchUsersByString;

  const isSelected = useCallback(
    (id) => {
      return participantId === id ? 'outline' : 'plain';
    },
    [participantId]
  );

  const RightElement = () => (loading ? <ActivityIndicator /> : <SearchIcon colorVariant="body" />);

  return (
    <Col mt="s" height={outerHeight}>
      <TextField
        isAutoComplete={false}
        sizeVariant="small"
        shapeVariant="round"
        variant="outline"
        colorVariant="base-02"
        value={queryString}
        onChangeText={setQueryString}
        placeholder="Search by name invite by email"
        rightElement={<RightElement />}
      />
      <Row
        flexWrap="wrap"
        maxHeight={maxHeight}
        py="s"
        justifyContent="flex-start"
        overflow="scroll"
      >
        {users?.map(({ firstName, userId, lastName }) => (
          <TouchableHighlight
            key={userId}
            underlayColor="transparent"
            onPress={() => setParticipantId(userId)}
          >
            <Card
              p="s"
              variant={isSelected(userId)}
              colorVariant="base"
              alignItems="center"
              width={115}
            >
              <>
                <Avatar
                  onPress={() => setParticipantId(userId)}
                  size={38}
                  status="online"
                  colorVariant="base-01"
                  shapeVariant="square"
                  uri="https://avatars.githubusercontent.com/u/98377997"
                />
                <Text mt="2xs" variant="caption" color="title" textAlign="center">
                  {firstName} {lastName}
                </Text>
              </>
            </Card>
          </TouchableHighlight>
        ))}
      </Row>
    </Col>
  );
};

type InviteType = {
  selected: string;
  participantId: string;
  setParticipantId: (value: string) => void;
};
