import { useCallback, useEffect } from 'react';
import { Col, StyleSystemThemedProps } from 'components/layout';
import { Text, Avatar, Chip, Visible, TouchableTile } from 'components';
import { RoomMember, RoomTypeEnum, useMultipleRoomsQuery } from 'expo-schema';
import { metrics } from 'config';
import { getActiveRoomId } from 'utils/room';
import { useProfile, useRouting } from 'hooks';

const { LIMITS } = metrics;

export const Direct: React.FC<AllRoomType> = ({ openRoom, ...props }) => {
  const { routeSegments } = useRouting();
  const { profile } = useProfile();
  const { data } = useMultipleRoomsQuery({
    variables: {
      input: {
        type: RoomTypeEnum.Direct,
        limit: LIMITS.rooms,
        offset: 0,
      },
    },
  });

  const getVariant = useCallback(
    (roomId) => {
      return routeSegments[0] === 'rooms' && routeSegments.includes(roomId) ? 'hover' : 'text';
    },
    [routeSegments]
  );
  const opnLastActiveRoom = useCallback(async () => {
    const lastActiveRoom = await getActiveRoomId();
    if (!lastActiveRoom) {
      const [firstRoom] = data?.multipleRooms || [];
      if (firstRoom) {
        openRoom(firstRoom.id);
      }
    }
  }, [data?.multipleRooms, openRoom]);

  useEffect(() => {
    opnLastActiveRoom();
  }, [opnLastActiveRoom]);

  const getRoomNameLogo = useCallback(
    (members: RoomMember[]): LogoResponseType => {
      const participantMember = members.find((member: RoomMember) => member.userId != profile?.id);
      const profileUrl = participantMember?.userProfilePhotoUrl;
      const profilePhotoUrl = profileUrl ? (profileUrl as string) : null;
      const name = participantMember?.userName.first as string;
      return { profilePhotoUrl, name };
    },
    [profile?.id]
  );

  const directRooms = data?.multipleRooms;
  const isDirectRooms = directRooms && directRooms?.length > 0;

  return (
    <Visible if={isDirectRooms}>
      <Col {...props}>
        <Text ml="xs" mt="m" mb="2xs" variant="caption" color="caption-01">
          DIRECT ROOMS
        </Text>
        {directRooms?.map((room) => (
          <Col key={room.id}>
            <TouchableTile
              mt="3xs"
              onPress={() => openRoom(room.id)}
              variant={getVariant(room.id)}
              title={getRoomNameLogo(room.members as RoomMember[]).name}
              px="xs"
              leftElement={
                <Avatar
                  status="online"
                  size={24}
                  colorVariant="base-02"
                  title={getRoomNameLogo(room.members as RoomMember[]).name}
                  shapeVariant="square"
                  uri={getRoomNameLogo(room.members as RoomMember[]).profilePhotoUrl}
                />
              }
              rightElement={
                <Visible if={false}>
                  <Chip
                    titleColor="white"
                    variant="plain"
                    sizeVariant="extra-small"
                    colorVariant="secondary"
                    title={room.countMembers?.toString()}
                  />
                </Visible>
              }
              sizeVariant="large"
            />
          </Col>
        ))}
      </Col>
    </Visible>
  );
};

type AllRoomType = StyleSystemThemedProps & DirectProps;
interface DirectProps {
  openRoom: (id: string) => void;
}

type LogoResponseType = {
  profilePhotoUrl: string | null;
  name: string;
};
