import { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  StyleSheet,
  Modal,
  Platform,
} from 'react-native';
import * as Clipboard from 'expo-clipboard';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { resolveAvatar } from '../../lib/resolveAvatar';
import { useColors } from '../../lib/theme';
import { useThemeStore } from '../../stores/theme';

export type ChatMsg = {
  id: string;
  userId: string;
  nickname?: string | null;
  avatar?: string | null;
  content: string;
  replyTo?: {
    id: string;
    userId: string;
    nickname?: string | null;
    content: string;
    attachmentType?: string | null;
  } | null;
  attachmentUrl?: string | null;
  attachmentType?: string | null;
  attachmentName?: string | null;
  likesCount: number;
  likedByMe?: boolean;
  createdAt: string;
  isOwn: boolean;
  readAt?: string | null;
};

type Props = {
  msg: ChatMsg;
  showName?: boolean;
  isFirstInGroup?: boolean;
  isLastInGroup?: boolean;
  hideReadStatus?: boolean;
  onReply: (msg: ChatMsg) => void;
  onLike: (msg: ChatMsg) => void;
  onOpenImage: (url: string) => void;
};

function formatTime(ts: string) {
  return new Date(ts).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
}

function useBubbleColors() {
  const colorScheme = useThemeStore((s) => s.colorScheme);
  const isDark = colorScheme === 'dark';
  return {
    ownBg: isDark ? '#1e4d3a' : '#D1F4CC',
    ownText: isDark ? '#e8f5e2' : '#0a0a0a',
    otherBg: isDark ? '#2c2c2e' : '#ffffff',
    otherText: isDark ? '#ffffff' : '#0a0a0a',
    replyBarColor: '#25D366',
    readColor: '#34B7F1',
  };
}

export function ChatBubble({
  msg,
  showName = false,
  isFirstInGroup = true,
  isLastInGroup = true,
  hideReadStatus = false,
  onReply,
  onLike,
  onOpenImage,
}: Props) {
  const { t } = useTranslation();
  const colors = useColors();
  const styles = makeStyles(colors);
  const bubbleColors = useBubbleColors();
  const [actionsOpen, setActionsOpen] = useState(false);

  const isImageOnly =
    !!msg.attachmentUrl && msg.attachmentType === 'image' && !msg.content && !msg.replyTo;
  const replyHasAttachment = msg.replyTo?.attachmentType === 'image';
  const avatarUrl = resolveAvatar(msg.avatar, msg.nickname ?? '?');

  const ownBubbleRadius = {
    borderTopLeftRadius: 14,
    borderTopRightRadius: isFirstInGroup ? 14 : 4,
    borderBottomLeftRadius: 14,
    borderBottomRightRadius: isLastInGroup ? 4 : 4,
  };

  const otherBubbleRadius = {
    borderTopLeftRadius: isFirstInGroup ? 14 : 4,
    borderTopRightRadius: 14,
    borderBottomLeftRadius: isLastInGroup ? 4 : 4,
    borderBottomRightRadius: 14,
  };

  const bubbleBg = msg.isOwn ? bubbleColors.ownBg : bubbleColors.otherBg;
  const bubbleText = msg.isOwn ? bubbleColors.ownText : bubbleColors.otherText;

  function copyContent() {
    if (msg.content) Clipboard.setStringAsync(msg.content);
    setActionsOpen(false);
  }

  return (
    <>
      <View
        style={[
          styles.row,
          { justifyContent: msg.isOwn ? 'flex-end' : 'flex-start' },
          { marginTop: isFirstInGroup ? 8 : 2 },
        ]}
      >
        {!msg.isOwn && (
          <View style={styles.avatarSlot}>
            {isLastInGroup ? (
              <Image source={{ uri: avatarUrl }} style={styles.avatar} />
            ) : null}
          </View>
        )}

        <View style={[styles.bubbleCol, { alignItems: msg.isOwn ? 'flex-end' : 'flex-start' }]}>
          {showName && !msg.isOwn && isFirstInGroup && (
            <Text style={styles.nickname} numberOfLines={1}>
              {msg.nickname ?? '?'}
            </Text>
          )}

          <TouchableOpacity
            delayLongPress={350}
            onLongPress={() => setActionsOpen(true)}
            activeOpacity={1}
            style={[
              styles.bubble,
              msg.isOwn ? ownBubbleRadius : otherBubbleRadius,
              { backgroundColor: bubbleBg },
              !msg.isOwn && styles.bubbleOtherBorder,
              isImageOnly && { padding: 4 },
            ]}
          >
            {msg.replyTo && (
              <TouchableOpacity
                activeOpacity={0.7}
                style={[
                  styles.replyPreview,
                  {
                    backgroundColor: msg.isOwn
                      ? 'rgba(0,0,0,0.08)'
                      : colors.surfaceElevated,
                    borderLeftColor: bubbleColors.replyBarColor,
                  },
                ]}
              >
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_700Bold',
                    color: bubbleColors.replyBarColor,
                  }}
                  numberOfLines={1}
                >
                  {msg.replyTo.nickname ?? '?'}
                </Text>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_400Regular',
                    color: colors.textMuted,
                    marginTop: 1,
                  }}
                  numberOfLines={1}
                >
                  {replyHasAttachment && (
                    <Ionicons name="image" size={11} color={colors.textMuted} />
                  )}{' '}
                  {msg.replyTo.content || (replyHasAttachment ? t('chat.image_attachment') : '…')}
                </Text>
              </TouchableOpacity>
            )}

            {msg.attachmentUrl && msg.attachmentType === 'image' && (
              <TouchableOpacity
                onPress={() => onOpenImage(msg.attachmentUrl!)}
                activeOpacity={0.7}
                style={[styles.imageWrap, msg.content ? { marginBottom: 4 } : null]}
              >
                <Image
                  source={{ uri: msg.attachmentUrl }}
                  style={styles.image}
                  resizeMode="cover"
                />
                {isImageOnly && (
                  <View style={styles.imageTimeOverlay}>
                    {msg.likesCount > 0 && (
                      <View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 4 }}>
                        <Ionicons name="heart" size={10} color="#f87171" />
                        <Text style={{ fontSize: 10, color: '#fff', marginLeft: 2 }}>
                          {msg.likesCount}
                        </Text>
                      </View>
                    )}
                    <Text style={{ fontSize: 10, color: '#fff' }}>{formatTime(msg.createdAt)}</Text>
                  </View>
                )}
              </TouchableOpacity>
            )}

            {msg.attachmentUrl && msg.attachmentType !== 'image' && (
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  paddingHorizontal: 10,
                  paddingVertical: 8,
                  borderRadius: 10,
                  marginBottom: 4,
                  backgroundColor: 'rgba(0,0,0,0.06)',
                }}
              >
                <Ionicons name="document-attach" size={18} color={colors.textMuted} />
                <Text
                  style={{
                    fontSize: 12,
                    fontFamily: 'Nunito_600SemiBold',
                    marginLeft: 8,
                    color: bubbleText,
                    flex: 1,
                  }}
                  numberOfLines={1}
                >
                  {msg.attachmentName ?? t('chat.file_attachment')}
                </Text>
              </View>
            )}

            {msg.content !== '' && (
              <Text style={[styles.content, { color: bubbleText }]}>
                {msg.content}
              </Text>
            )}

            {!isImageOnly && (
              <View style={styles.footer}>
                {msg.likesCount > 0 && (
                  <View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 4 }}>
                    <Ionicons name="heart" size={10} color="#f87171" />
                    <Text
                      style={{
                        fontSize: 10,
                        marginLeft: 2,
                        fontFamily: 'Nunito_600SemiBold',
                        color: colors.textMuted,
                      }}
                    >
                      {msg.likesCount}
                    </Text>
                  </View>
                )}
                <Text
                  style={{
                    fontSize: 10,
                    fontFamily: 'Nunito_400Regular',
                    color: msg.isOwn ? 'rgba(0,0,0,0.45)' : colors.textMuted,
                  }}
                >
                  {formatTime(msg.createdAt)}
                </Text>
                {msg.isOwn && !hideReadStatus && (
                  <Ionicons
                    name={msg.readAt ? 'checkmark-done' : 'checkmark'}
                    size={12}
                    color={msg.readAt ? bubbleColors.readColor : 'rgba(0,0,0,0.35)'}
                    style={{ marginLeft: 2 }}
                  />
                )}
              </View>
            )}
          </TouchableOpacity>
        </View>
      </View>

      <Modal
        visible={actionsOpen}
        transparent
        animationType="fade"
        onRequestClose={() => setActionsOpen(false)}
      >
        <TouchableOpacity style={styles.sheetBackdrop} onPress={() => setActionsOpen(false)} activeOpacity={1}>
          <TouchableOpacity style={styles.sheet} onPress={() => {}} activeOpacity={1}>
            <View style={styles.sheetGrabber} />
            <TouchableOpacity
              style={styles.sheetItem}
              onPress={() => {
                setActionsOpen(false);
                onReply(msg);
              }}
              activeOpacity={0.7}
            >
              <Ionicons name="arrow-undo" size={18} color="#007AFF" />
              <Text style={styles.sheetText}>{t('chat.reply')}</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.sheetItem}
              onPress={() => {
                setActionsOpen(false);
                onLike(msg);
              }}
              activeOpacity={0.7}
            >
              <Ionicons
                name={msg.likedByMe ? 'heart' : 'heart-outline'}
                size={18}
                color={msg.likedByMe ? '#f87171' : '#007AFF'}
              />
              <Text style={styles.sheetText}>
                {msg.likedByMe ? t('chat.unlike') : t('chat.like')}
              </Text>
            </TouchableOpacity>
            {msg.content !== '' && (
              <TouchableOpacity style={styles.sheetItem} onPress={copyContent} activeOpacity={0.7}>
                <Ionicons name="copy-outline" size={18} color="#007AFF" />
                <Text style={styles.sheetText}>{t('chat.copy')}</Text>
              </TouchableOpacity>
            )}
          </TouchableOpacity>
        </TouchableOpacity>
      </Modal>
    </>
  );
}

function makeStyles(colors: ReturnType<typeof useColors>) {
  return StyleSheet.create({
    row: {
      flexDirection: 'row',
      paddingHorizontal: 10,
    },
    avatarSlot: {
      width: 32,
      marginRight: 6,
      justifyContent: 'flex-end',
    },
    avatar: {
      width: 28,
      height: 28,
      borderRadius: 14,
      backgroundColor: colors.surfaceElevated,
    },
    bubbleCol: {
      maxWidth: '76%',
    },
    nickname: {
      fontSize: 11,
      fontFamily: 'Nunito_700Bold',
      color: '#25D366',
      marginBottom: 3,
      marginLeft: 12,
    },
    bubble: {
      paddingHorizontal: 12,
      paddingTop: 8,
      paddingBottom: 6,
      shadowColor: '#000',
      shadowOpacity: 0.08,
      shadowRadius: 3,
      shadowOffset: { width: 0, height: 1 },
      elevation: 1,
    },
    bubbleOtherBorder: {
      borderWidth: StyleSheet.hairlineWidth,
      borderColor: 'rgba(0,0,0,0.06)',
    },
    replyPreview: {
      borderLeftWidth: 4,
      borderRadius: 6,
      paddingHorizontal: 8,
      paddingVertical: 4,
      marginBottom: 6,
    },
    imageWrap: {
      borderRadius: 10,
      overflow: 'hidden',
      position: 'relative',
    },
    image: {
      width: 220,
      height: 220,
      backgroundColor: colors.surfaceElevated,
    },
    imageTimeOverlay: {
      position: 'absolute',
      bottom: 6,
      right: 6,
      backgroundColor: 'rgba(0,0,0,0.5)',
      borderRadius: 10,
      paddingHorizontal: 6,
      paddingVertical: 2,
      flexDirection: 'row',
      alignItems: 'center',
    },
    content: {
      fontSize: 14,
      lineHeight: 21,
      fontFamily: 'Nunito_400Regular',
    },
    footer: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'flex-end',
      gap: 3,
      marginTop: 4,
      alignSelf: 'flex-end',
    },
    sheetBackdrop: {
      flex: 1,
      backgroundColor: 'rgba(0,0,0,0.35)',
      justifyContent: 'flex-end',
    },
    sheet: {
      backgroundColor: colors.bg,
      borderTopLeftRadius: 22,
      borderTopRightRadius: 22,
      padding: 8,
      paddingBottom: Platform.OS === 'ios' ? 34 : 16,
    },
    sheetGrabber: {
      width: 36,
      height: 4,
      borderRadius: 2,
      backgroundColor: colors.border,
      alignSelf: 'center',
      marginBottom: 10,
    },
    sheetItem: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: 16,
      paddingVertical: 14,
      borderRadius: 12,
    },
    sheetText: {
      fontSize: 15,
      fontFamily: 'Nunito_600SemiBold',
      color: colors.text,
      marginLeft: 12,
    },
  });
}
