import { useCallback } from 'react';
import { Container, Row, ScrollView } from 'components/layout';
import { metrics } from 'config';
import { topEmojis } from 'emojis';
import { BottomSheet } from 'components/bottom-sheet';
import { ReplyThread, QuoteReply, CopyLink, Pencil, Trash, More, SmilingOutlineAdd } from 'icons';
import { TouchableTile, Text, Divider, Fab, Card, Visible } from 'components';
import { ColorName } from '@emotion/react';
import { useResponsiveLayout } from 'hooks';
import { isEmojisOpenVar, isMessageMoreActionOpenVar } from 'state-management/dialogs';
import {
  deletingMessageIdVar,
  editingMessageIdVar,
  isEditingMessageVar,
  messageMoreActionsPositionVar,
  selectedMessageIdVar,
} from 'state-management/chat';

const { STYLES, Z_INDEX } = metrics;
const sheetHeight = 350;
const additionInPosition = 20;
export const MessageAction: React.FC<MessageActionProps> = ({
  isSheetOpen = false,
  isHovered,
  position,
  messageId,
  setIsSheetOpen,
  openEmojisSheet,
}) => {
  const { isMobile, height } = useResponsiveLayout();

  const handleEmojisOpen = useCallback(() => {
    if (openEmojisSheet) {
      openEmojisSheet();
    }
  }, [openEmojisSheet]);

  const closeSheet = useCallback(() => {
    if (setIsSheetOpen) {
      setIsSheetOpen(false);
    }
  }, [setIsSheetOpen]);

  const deleteMessage = useCallback(() => {
    deletingMessageIdVar(messageId);
  }, [messageId]);

  const editMessage = useCallback(() => {
    editingMessageIdVar(messageId);
    isEditingMessageVar(true);
  }, [messageId]);

  const actions: ActionType[] = [
    {
      id: 1,
      title: 'Reply in Thread',
      leftElement: <ReplyThread />,
    },
    {
      id: 2,
      title: 'Quote Reply',
      leftElement: <QuoteReply />,
    },
  ];

  const editActions: ActionType[] = [
    {
      id: 3,
      title: 'Copy Link',
      onPress: () => {},
      leftElement: <CopyLink />,
    },
    {
      id: 4,
      onPress: editMessage,
      title: 'Edit Message',
      leftElement: <Pencil />,
    },
    {
      id: 5,
      onPress: deleteMessage,
      title: 'Delete Message',
      leftElement: <Trash />,
      titleColor: 'secondary',
    },
  ];

  const openMore = useCallback(() => {
    if (position) {
      const half = height / 2;

      const isDown = half < position?.y;
      if (isDown) {
        const bottomPortion = height - position.y + additionInPosition;
        messageMoreActionsPositionVar({ bottom: bottomPortion, top: undefined, x: position.x });
      } else {
        const top = position.y + additionInPosition;
        messageMoreActionsPositionVar({ bottom: undefined, top, x: position.x });
      }
    }

    isMessageMoreActionOpenVar(true);
    selectedMessageIdVar(messageId);
  }, [height, messageId, position]);

  const openEmojis = useCallback(() => {
    isEmojisOpenVar(true);
  }, []);
  return (
    <>
      {!isMobile ? (
        <Visible if={isHovered}>
          <Card
            colorVariant="base"
            zIndex={Z_INDEX.messageAction}
            variant="outline"
            position="absolute"
            right={20}
            top={-20}
          >
            <Row p="3xs">
              <Fab
                onPress={openEmojis}
                variant="plain"
                sizeVariant="small"
                shapeVariant="round"
                hoverColorVariant="base-02-hover"
                colorVariant="transparent"
                centerElement={<SmilingOutlineAdd />}
              />
              <Fab
                onPress={() => {}}
                variant="plain"
                sizeVariant="small"
                shapeVariant="round"
                hoverColorVariant="base-02-hover"
                colorVariant="transparent"
                centerElement={<ReplyThread />}
              />
              <Fab
                onPress={() => {}}
                variant="plain"
                sizeVariant="small"
                shapeVariant="round"
                hoverColorVariant="base-02-hover"
                colorVariant="transparent"
                centerElement={<QuoteReply />}
              />
              <Fab
                onPress={openMore}
                variant="plain"
                sizeVariant="small"
                shapeVariant="round"
                hoverColorVariant="base-02-hover"
                colorVariant="transparent"
                centerElement={<More colorVariant="title" />}
              />
            </Row>
          </Card>
        </Visible>
      ) : (
        <BottomSheet isSheetOpen={isSheetOpen} height={sheetHeight} closeSheet={closeSheet}>
          <Container borderRadius={STYLES.radius.card} backgroundColor="base-01" flexGrow={1}>
            <ScrollView height={300}>
              <Row px="s" pt="m" pb="2xs" flexGrow={1} justifyContent="space-between">
                {topEmojis.map((emoji) => {
                  return (
                    <Fab
                      onPress={() => {}}
                      variant="plain"
                      sizeVariant="medium"
                      colorVariant="base"
                      centerElement={<Text variant="title">{emoji}</Text>}
                    />
                  );
                })}
                <Fab
                  onPress={handleEmojisOpen}
                  variant="plain"
                  sizeVariant="medium"
                  colorVariant="base"
                  centerElement={<SmilingOutlineAdd />}
                />
              </Row>
              <Divider my="xs" colorVariant="divider-01" directionVariant="horizontal" size={1} />

              {actions.map(({ title, titleColor, leftElement }) => {
                return (
                  <TouchableTile
                    onPress={() => {}}
                    mx="xs"
                    variant="text"
                    sizeVariant="large"
                    underlayColorVariant="base-02"
                    centerElement={
                      <Row alignItems="center">
                        <Visible if={!!leftElement}>
                          <Container mr="s">{leftElement}</Container>
                        </Visible>
                        <Text variant="title" color={titleColor || 'body'} weightVariant="normal">
                          {title}
                        </Text>
                        <Divider colorVariant="divider-01" directionVariant="horizontal" />
                      </Row>
                    }
                  />
                );
              })}

              <Divider my="xs" colorVariant="divider-01" directionVariant="horizontal" size={1} />
              {editActions.map(({ title, titleColor, leftElement }) => {
                return (
                  <TouchableTile
                    onPress={() => {}}
                    variant="text"
                    mx="xs"
                    sizeVariant="large"
                    centerElement={
                      <Row alignItems="center">
                        <Visible if={!!leftElement}>
                          <Container mr="s">{leftElement}</Container>
                        </Visible>
                        <Text variant="title" color={titleColor || 'body'} weightVariant="normal">
                          {title}
                        </Text>
                        <Divider colorVariant="divider-01" directionVariant="horizontal" />
                      </Row>
                    }
                  />
                );
              })}
            </ScrollView>
          </Container>
        </BottomSheet>
      )}
    </>
  );
};

interface ActionType {
  id: number;
  title?: string;
  caption?: string;
  titleColor?: ColorName;
  onPress?: () => void;
  leftElement?: JSX.Element;
}

export interface MessageActionProps {
  messageId: string;
  position: DOMRect | null;
  isSheetOpen?: boolean;
  isHovered?: boolean;
  setIsSheetOpen?: (value: boolean) => void;
  openEmojisSheet?: () => void;
}
