import React, { useState, useEffect } from 'react'
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  Image,
  BackHandler,
  ActivityIndicator,
  ScrollView,
} from 'react-native'
import appColors from '../../../theme/appColors'
import { useValues } from '../../../utils/context'
import { styles } from './styles'
import { useNavigation, useRoute, useTheme } from '@react-navigation/native'
import Icons from '../../../utils/icons/icons'
import Images from '../../../utils/images/images'
import { useSelector } from 'react-redux'
import { useAppNavigation } from '../../../utils/navigation'
import { initializeApp } from 'firebase/app'
import {
  getFirestore,
  collection,
  doc,
  addDoc,
  setDoc,
  updateDoc,
  query,
  orderBy,
  onSnapshot,
  serverTimestamp,
  deleteDoc,
  getDocs,
} from 'firebase/firestore'
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage'
import { launchImageLibrary } from 'react-native-image-picker'
import { firebaseConfig } from '../../../../firebase'
import { windowHeight, windowWidth } from '../../../theme/appConstant'

const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const storage = getStorage(app)

export function Chat() {
  const route = useRoute()
  const { driverId, riderId, rideId, riderName, riderImage, from }: any =
    route.params || {}
  const { goBack } = useAppNavigation()
  const { colors } = useTheme()
  const { viewRtlStyle, textRtlStyle, rtl, isDark } = useValues()
  const { translateData } = useSelector((state: any) => state.setting)
  const { self } = useSelector((state: any) => state.account)
  const navigation = useNavigation()

  const [messages, setMessages] = useState<any[]>([])
  const [input, setInput] = useState<string>('')
  const [uploading, setUploading] = useState<boolean>(false)
  const [selectedImages, setSelectedImages] = useState<string[]>([])

  useEffect(() => {
    const backAction = () => {
      if (navigation.canGoBack()) {
        navigation.goBack()
        return true
      }
      return false
    }
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    )
    return () => backHandler.remove()
  }, [navigation])

  const selfId = `${driverId}`
  const chatWithUserId = from === 'help' ? '1' : `${riderId}`
  const ride_Id = `${rideId}`
  const currentUserId = `${driverId}`
  const chatId =
    from === 'help'
      ? [selfId, chatWithUserId].sort().join('_')
      : [ride_Id, selfId, chatWithUserId].sort().join('_')

  const messagesRef = collection(db, 'chats', chatId, 'messages')

  useEffect(() => {
    const q = query(messagesRef, orderBy('timestamp', 'desc'))
    const unsubscribe = onSnapshot(q, snapshot => {
      const fetchedMessages = snapshot.docs.map(doc => ({
        id: doc.id,
        ...doc.data(),
      }))
      setMessages(fetchedMessages)
    })
    return () => unsubscribe()
  }, [chatId])

  const pickImages = async () => {
    launchImageLibrary({ mediaType: 'photo', selectionLimit: 5 }, response => {
      if (response.didCancel) return
      if (response.errorMessage) return
      if (response.assets && response.assets.length > 0) {
        const uris = response.assets.map(asset => asset.uri!).filter(Boolean)
        setSelectedImages(prev => [...prev, ...uris])
      }
    })
  }

  const uriToBlob = (uri: string) =>
    new Promise<Blob>((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.onload = () => resolve(xhr.response)
      xhr.onerror = () => reject(new Error('uriToBlob failed'))
      xhr.responseType = 'blob'
      xhr.open('GET', uri, true)
      xhr.send(null)
    })

  const uploadImagesToStorage = async (uris: string[]) => {
    const urls: string[] = []
    setUploading(true)
    try {
      for (const uri of uris) {
        const filename = `${chatId}/${Date.now()}_${Math.random()}.jpg`
        const storageRef = ref(storage, `chatImages/${filename}`)
        const blob = await uriToBlob(uri)
        await uploadBytes(storageRef, blob)
        const downloadURL = await getDownloadURL(storageRef)
        urls.push(downloadURL)
      }
    } catch (err) {}
    setUploading(false)
    return urls
  }

 const sendMessage = async () => {
  if (!input.trim() && selectedImages.length === 0) return

  const messageText = input.trim()
  const imagesToSend = [...selectedImages]

  // 🔥 IMMEDIATELY clear UI
  setInput('')
  setSelectedImages([])

  try {
    const imageUrls =
      imagesToSend.length > 0
        ? await uploadImagesToStorage(imagesToSend)
        : []

    const receiverId = from === 'help' ? '1' : riderId
    const receiverName = from === 'help' ? 'Administrator' : riderName

    const messageData: any = {
      senderId: selfId,
      senderName: self?.name || 'Driver',
      receiverId,
      receiverName,
      timestamp: serverTimestamp(),
      message: messageText,
      images: imageUrls || [],
    }

    await addDoc(messagesRef, messageData)

    await setDoc(
      doc(db, 'chats', chatId),
      {
        lastMessage: messageData,
        participants: [selfId, receiverId],
        unreadCount: { [receiverId]: 1, [selfId]: 0 },
        is_chatRoom: { [selfId]: 1, [receiverId]: 0 },
      },
      { merge: true },
    )
  } catch (err) {
    console.log('send error', err)
  }
}


  useEffect(() => {
    updateDoc(doc(db, 'chats', chatId), { [`unreadCount.${selfId}`]: 0 }).catch(
      console.log,
    )
  }, [chatId, selfId])

  const [open, setOpen] = useState<boolean>(false)

  const clearChat = async () => {
    try {
      const querySnapshot = await getDocs(messagesRef)

      const deletePromises = querySnapshot.docs.map(docItem =>
        deleteDoc(docItem.ref),
      )
      await Promise.all(deletePromises)

      setMessages([])

      await updateDoc(doc(db, 'chats', chatId), {
        lastMessage: null,
        [`unreadCount.${selfId}`]: 0,
      })

      setOpen(false)
    } catch (error) {
      setOpen(false)
      console.error('Error clearing chat:', error)
    }
  }

  return (
    <View
      style={[styles.containerMain, { backgroundColor: colors.background }]}
    >
      <View
        style={[
          styles.view_Main,
          { backgroundColor: colors.card, flexDirection: viewRtlStyle },
        ]}
      >
        <View style={{ flexDirection: viewRtlStyle }}>
          <TouchableOpacity
            activeOpacity={0.7}
            style={[
              styles.backButton,
              { backgroundColor: colors.card, borderColor: colors.border },
            ]}
            onPress={goBack}
          >
            <Icons.Back color={colors.text} />
          </TouchableOpacity>
          <View style={styles.riderContainer}>
            <Text
              style={[
                styles.templetionStyle,
                { textAlign: textRtlStyle, color: colors.text },
              ]}
            >
              {from === 'help' ? 'Administrator' : riderName}
            </Text>
            <Text style={[styles.onlineText, { textAlign: textRtlStyle }]}>
              {translateData.online}
            </Text>
          </View>
        </View>
      </View>

      {open && (
        <View
          style={[
            styles.box,
            {
              backgroundColor: colors.card,
              alignSelf: rtl ? 'flex-start' : 'flex-end',
            },
          ]}
        >
          <Text style={{ color: colors.text }}>{translateData?.callNow}</Text>
          <View style={[styles.line, { backgroundColor: colors.border }]} />
          <Text style={{ color: colors.text }} onPress={clearChat}>
            {translateData?.clearChat}
          </Text>
        </View>
      )}

      <FlatList
        inverted
        data={messages}
        keyExtractor={item => item.id}
        style={styles.listContainer}
        renderItem={({ item }) => {
          const timestamp = item.timestamp?.seconds
            ? new Date(item.timestamp.seconds * 1000).toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit',
                hour12: true,
              })
            : translateData.sending

          return (
            <View
              style={[
                styles.mainContainer,
                {
                  flexDirection:
                    item.senderId === selfId ? 'row-reverse' : 'row',
                },
              ]}
            >
              {item.senderId !== selfId && (
                <Image
                  source={
                    riderImage ? { uri: riderImage } : Images.ProfileDefault
                  }
                  style={[styles.image, { borderColor: colors.border }]}
                />
              )}
              <View
                style={[
                  styles.messageContainer,
                  item.senderId === selfId
                    ? [
                        styles.senderMessage,
                        {
                          backgroundColor: isDark
                            ? appColors.primaryFont
                            : appColors.black,
                        },
                      ]
                    : [
                        styles.receiverMessage,
                        {
                          backgroundColor: isDark
                            ? appColors.secondaryDark
                            : appColors.white,
                        },
                      ],
                ]}
              >
                {item.message && (
                  <Text
                    style={[
                      styles.messageText,
                      item.senderId !== selfId
                        ? [
                            {
                              color: isDark
                                ? appColors.white
                                : appColors.primaryFont,
                            },
                            { textAlign: rtl ? 'right' : 'left' },
                          ]
                        : [
                            {
                              color: isDark
                                ? appColors.white
                                : appColors.graybackground,
                            },
                          ],
                    ]}
                  >
                    {item.message}
                  </Text>
                )}
                {item.images && Array.isArray(item.images) && (
                  <View
                    style={{
                      flexDirection: 'row',
                      flexWrap: 'wrap',
                      marginTop: 5,
                    }}
                  >
                    {item.images.map((img: string, idx: number) => (
                      <Image
                        key={idx}
                        source={{ uri: img }}
                        style={{
                          width: 120,
                          height: 120,
                          borderRadius: 8,
                          margin: 3,
                        }}
                      />
                    ))}
                  </View>
                )}
                <View
                  style={{
                    flexDirection: viewRtlStyle,
                    alignItems: 'center',
                    justifyContent: 'flex-end',
                  }}
                >
                  {item.senderId === selfId && (
                    <View
                      style={{
                        marginHorizontal: windowWidth(1),
                        marginTop: windowHeight(0.8),
                      }}
                    >
                      <Icons.Recive />
                    </View>
                  )}
                  <Text
                    style={[
                      styles.messageText,
                      item.senderId !== currentUserId
                        ? [
                            styles.senderMessageTime,
                            { textAlign: rtl ? 'right' : 'left' },
                          ]
                        : [
                            styles.receiverMessageTime,
                            { textAlign: rtl ? 'left' : 'right' },
                          ],
                    ]}
                  >
                    {timestamp}
                  </Text>
                </View>
              </View>
            </View>
          )
        }}
      />

      {selectedImages.length > 0 && (
        <ScrollView
          horizontal
          style={{
            marginHorizontal: windowWidth(5),
            paddingBottom: windowWidth(9),
          }}
        >
          {selectedImages.map((uri, idx) => (
            <Image
              key={idx}
              source={{ uri }}
              style={{ width: 70, height: 70, borderRadius: 8, marginRight: 5 }}
            />
          ))}
        </ScrollView>
      )}

      <View
        style={[
          styles.inputContainer,
          { backgroundColor: colors.background, flexDirection: viewRtlStyle },
        ]}
      >
        <View
          style={[
            styles.textInputView,
            { backgroundColor: colors.card, flexDirection: viewRtlStyle },
          ]}
        >
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={pickImages}
            style={{ marginHorizontal: windowWidth(2) }}
          >
            <Icons.ImagePick />
          </TouchableOpacity>
          <TextInput
            style={[
              styles.input,
              { textAlign: textRtlStyle, color: colors.text },
            ]}
            value={input}
            onChangeText={setInput}
            placeholder={translateData.typeHere}
            multiline
            placeholderTextColor={appColors.secondaryFont}
          />
          {uploading ? (
            <ActivityIndicator
              size="small"
              color={isDark ? appColors.black : appColors.white}
            />
          ) : (
            <TouchableOpacity
              style={[styles.sendButton, { backgroundColor: colors.text }]}
              onPress={sendMessage}
              activeOpacity={0.7}
            >
              <Icons.SendChat
                color={isDark ? appColors.black : appColors.white}
              />
            </TouchableOpacity>
          )}
        </View>
      </View>
    </View>
  )
}
