/* eslint-disable @typescript-eslint/ban-ts-comment */
import { FC, useCallback, useEffect, useState } from 'react';
import { Col, Container, Row, ScrollView } from 'components/layout';
import { Visible } from 'components/visible';
import { Divider } from 'components/divider';
import { Button } from 'components/button';
import { Dots } from 'components/dots';
import { isCreateRoomOpenVar } from 'state-management/dialogs';
import { doAlert } from 'utils/alert';
import { useProfile, useResponsiveLayout, useRouting } from 'hooks';
import { useReactiveVar } from '@apollo/client';
import {
  CreateRoomMemberMutation,
  CreateRoomMutation,
  RoomMemberRoleEnum,
  RoomMemberStatusEnum,
  RoomTypeEnum,
  useCreateRoomMemberMutation,
  useCreateRoomMutation,
} from 'expo-schema';
import { Invite } from '../invite';
import { Types } from '../types';
import { Group } from '../group';

export const Root: FC<RootType> = ({ tabIndex, setTabIndex, setRoomTypeParent }) => {
  const [dotCount, setDotCount] = useState(0);
  const [roomId, setRoomId] = useState('');
  const [roomType, setRoomType] = useState(RoomTypeEnum.Direct);
  const [type, setType] = useState(RoomTypeEnum.Chat);
  const [recordAutomatically, setRecordAutomatically] = useState(false);
  const [hideRecordingsDefault, setHideRecordingsDefault] = useState(false);
  const [participantId, setParticipantId] = useState('');
  const [name, setName] = useState('');
  const [topic, setTopic] = useState('');
  const { isMobile, isHandHeld } = useResponsiveLayout();
  const { profile } = useProfile();
  const { navigateBack } = useRouting();
  const createRoomOpen = useReactiveVar(isCreateRoomOpenVar);

  useEffect(() => {
    if (!createRoomOpen) {
      setTabIndex(0);
    }
  }, [createRoomOpen, setTabIndex]);

  const [createRoomMember, { loading: loadingCreateRoomMember }] = useCreateRoomMemberMutation({
    onCompleted: (data: CreateRoomMemberMutation) => {
      if (data.createRoomMember.member.role === RoomMemberRoleEnum.Host) {
        createRoomMember({
          variables: {
            input: {
              userId: participantId,
              roomId,
              role: RoomMemberRoleEnum.Participant,
              status: RoomMemberStatusEnum.Active,
            },
          },
        });
      } else {
        doAlert({ variant: 'success', message: 'Room Created successfully' });
        isCreateRoomOpenVar(false);
        if (isHandHeld) {
          navigateBack();
        }
      }
    },
  });

  const onCompleted = useCallback(
    (data: CreateRoomMutation) => {
      setRoomId(data.createRoom.room.id);
      createRoomMember({
        variables: {
          input: {
            userId: profile?.id as string,
            roomId: data.createRoom.room.id,
            role: RoomMemberRoleEnum.Host,
            status: RoomMemberStatusEnum.Active,
          },
        },
      });
    },
    [createRoomMember, profile?.id]
  );

  const [createRoomMutation, { loading }] = useCreateRoomMutation({
    onCompleted,
  });

  const mt = undefined;
  const isFirst = tabIndex === 0;
  const is2nd = tabIndex === 1;
  const is3rd = tabIndex === 2;
  const roomMutationType = roomType === RoomTypeEnum.Direct ? roomType : type;

  const isCreateRoom = is3rd ? true : is2nd && RoomTypeEnum.Direct === roomType;
  const isSecondInvite = tabIndex === 1 && roomType === RoomTypeEnum.Direct;
  const isSecondGroup = tabIndex === 1 && roomType !== RoomTypeEnum.Direct;

  const isLoading = loadingCreateRoomMember || loading;

  useEffect(() => {
    const isDirect = roomType === RoomTypeEnum.Direct;
    const count = isDirect ? 2 : 3;
    setDotCount(count);
  }, [tabIndex, roomType]);

  const handleType = useCallback((typeParam: string) => {
    setType(typeParam as RoomTypeEnum);
  }, []);

  const handleNext = useCallback(() => {
    setTabIndex(tabIndex + 1);
  }, [setTabIndex, tabIndex]);

  const closeDialog = useCallback(() => {
    isCreateRoomOpenVar(false);
  }, []);

  const createRoom = useCallback(() => {
    createRoomMutation({
      variables: {
        input: {
          name,
          type: roomMutationType,
          topic,
          recordAutomatically,
          hideRecordingsDefault,
        },
      },
    });
  }, [
    createRoomMutation,
    hideRecordingsDefault,
    name,
    recordAutomatically,
    roomMutationType,
    topic,
  ]);

  const handleRoomType = useCallback(
    (value: string) => {
      if (setRoomTypeParent) {
        setRoomTypeParent(value as RoomTypeEnum);
      }
      setRoomType(value as RoomTypeEnum);
    },
    [setRoomTypeParent]
  );

  const First = useCallback(() => {
    return (
      <Visible if={isFirst}>
        <Types type={roomType} setRoomType={handleRoomType} />
      </Visible>
    );
  }, [handleRoomType, isFirst, roomType]);

  const Third = useCallback(() => {
    return tabIndex === 2 && roomType !== RoomTypeEnum.Direct ? (
      <Invite selected={type} participantId={participantId} setParticipantId={setParticipantId} />
    ) : null;
  }, [participantId, roomType, tabIndex, type]);

  return (
    <Container flex={1}>
      <ScrollView
        contentContainerStyle={{
          padding: 0,
        }}
        flex={1}
        px="s"
      >
        <First />
        <Visible if={isSecondInvite}>
          <Invite
            selected={type}
            participantId={participantId}
            setParticipantId={setParticipantId}
          />
        </Visible>
        <Visible if={isSecondGroup}>
          <Group
            type={type}
            setType={handleType}
            name={name}
            setName={setName}
            topic={topic}
            setTopic={setTopic}
            recordAutomatically={recordAutomatically}
            setRecordAutomatically={setRecordAutomatically}
            hideRecordingsDefault={hideRecordingsDefault}
            setHideRecordingsDefault={setHideRecordingsDefault}
          />
        </Visible>
        <Third />
      </ScrollView>
      <Col mt={mt}>
        <Divider colorVariant="divider-02" />
        <Row mx="s" mt="m" alignItems="center" justifyContent="space-between">
          <Row>
            <Button
              onPress={closeDialog}
              colorVariant="base-02"
              sizeVariant="large"
              title="Cancel"
              titleColor="body"
              width={150}
            />
          </Row>
          <Visible if={!isMobile}>
            <Row>
              <Dots
                flexDirectionVariant="row"
                count={dotCount}
                selectedIndex={tabIndex}
                setSelectedIndex={setTabIndex}
              />
            </Row>
          </Visible>
          <Row>
            <Visible if={!isCreateRoom}>
              <Button
                ml="xs"
                colorVariant="primary"
                sizeVariant="large"
                title="Next"
                onPress={handleNext}
                width={150}
              />
            </Visible>
            <Visible if={isCreateRoom}>
              <Button
                ml="xs"
                loading={isLoading}
                onPress={createRoom}
                colorVariant="primary"
                sizeVariant="large"
                title="Create Room"
                width={150}
              />
            </Visible>
          </Row>
        </Row>
      </Col>
    </Container>
  );
};

type RootType = {
  tabIndex: number;
  setRoomTypeParent?: (value: RoomTypeEnum) => void;
  setTabIndex: (value: number) => void;
};
