import {FunctionComponent, memo, useEffect, useState} from 'react'
import {View} from 'react-native'
import {Gesture, GestureDetector} from 'react-native-gesture-handler'
import {runOnJS} from 'react-native-reanimated'

import {useDeleteMessage, useUpdateMessageContent} from '@/api/messages'
import useUser from '@/hooks/useUser'
import {IMessage} from '@/models/IMessage'
import {Card} from '@/components/ui/card'
import {Input, InputField} from '@/components/ui/input'
import {
  Actionsheet,
  ActionsheetBackdrop,
  ActionsheetContent,
  ActionsheetDragIndicator,
  ActionsheetDragIndicatorWrapper,
  ActionsheetIcon,
  ActionsheetItem,
  ActionsheetItemText,
} from '@/components/ui/actionsheet'
import {Avatar, AvatarImage} from '@/components/ui/avatar'
import {Text} from '@/components/ui/text'
import {Pencil, Trash} from 'lucide-react-native'
import {HStack} from '@/components/ui/hstack'
import {cn} from '@gluestack-ui/nativewind-utils/cn'

interface MessageProps extends IMessage {
  alignRight?: boolean
  channel: string
}

const Message: FunctionComponent<MessageProps> = ({
  id,
  content,
  profilePicture,
  alignRight,
  userName,
  userId,
  channel,
}) => {
  const [showMenu, setShowMenu] = useState<boolean>(false)
  const [isEditing, setIsEditing] = useState<boolean>(false)
  const [editedContent, setEditedContent] = useState<string>(content)
  const user = useUser()
  const {mutate: deleteMessage} = useDeleteMessage()
  const {mutate: updateMessageContent} = useUpdateMessageContent()

  useEffect(() => {
    setEditedContent(content)
  }, [content, id])

  const toggleShowMenu = () => {
    setShowMenu(x => !x)
  }

  const longPress = Gesture.LongPress()
    .minDuration(200)
    .onStart(() => runOnJS(toggleShowMenu)())
    .enabled(userId === user?.uid)

  return (
    <>
      <GestureDetector gesture={longPress}>
        <Card className={cn('w-[80%] my-2 p-2', {'self-end': alignRight})}>
          <HStack className="items-start">
            <View>
              <Avatar size="md">
                <AvatarImage source={{uri: profilePicture}} />
              </Avatar>
            </View>
            <View className="mx-2">
              <Text>{userName}</Text>
            </View>
          </HStack>
          <View className="my-2">
            {isEditing && (
              <Input>
                <InputField
                  value={editedContent}
                  onChangeText={setEditedContent}
                  autoFocus
                  onBlur={() => {
                    setIsEditing(false)
                    updateMessageContent({id: id!, content: editedContent, channel})
                  }}
                />
              </Input>
            )}
            {!isEditing && <Text>{editedContent}</Text>}
          </View>
        </Card>
      </GestureDetector>

      <Actionsheet isOpen={showMenu} onClose={() => setShowMenu(false)}>
        <ActionsheetBackdrop />
        <ActionsheetContent>
          <ActionsheetDragIndicatorWrapper>
            <ActionsheetDragIndicator />
          </ActionsheetDragIndicatorWrapper>
          <ActionsheetItem
            onPress={() => {
              deleteMessage({id: id!, channel})
              setShowMenu(false)
            }}>
            <ActionsheetIcon className="stroke-background-700" as={Trash} />
            <ActionsheetItemText>Delete</ActionsheetItemText>
          </ActionsheetItem>
          <ActionsheetItem
            onPress={() => {
              setIsEditing(true)
              setShowMenu(false)
            }}>
            <ActionsheetIcon className="stroke-background-700" as={Pencil} />
            <ActionsheetItemText>Edit</ActionsheetItemText>
          </ActionsheetItem>
        </ActionsheetContent>
      </Actionsheet>
    </>
  )
}

export default memo(Message)
