import AlertKonfirmasi from "@/components/alertKonfirmasi";
import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import HeaderRightDiscussionGeneralDetail from "@/components/discussion_general/headerDiscussionDetail";
import DrawerBottom from "@/components/drawerBottom";
import ImageUser from "@/components/imageNew";
import { InputForm } from "@/components/inputForm";
import LabelStatus from "@/components/labelStatus";
import MenuItemRow from "@/components/menuItemRow";
import Skeleton from "@/components/skeleton";
import SkeletonContent from "@/components/skeletonContent";
import Text from '@/components/Text';
import { ColorsStatus } from "@/constants/ColorsStatus";
import { ConstEnv } from "@/constants/ConstEnv";
import { regexOnlySpacesOrEnter } from "@/constants/OnlySpaceOrEnter";
import Styles from "@/constants/Styles";
import { apiDeleteDiscussionGeneralCommentar, apiGetDiscussionGeneralOne, apiSendDiscussionGeneralCommentar, apiUpdateDiscussionGeneralCommentar } from "@/lib/api";
import { getDB } from "@/lib/firebaseDatabase";
import { useAuthSession } from "@/providers/AuthProvider";
import { Feather, Ionicons, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import { ref } from '@react-native-firebase/database';
import { useHeaderHeight } from '@react-navigation/elements';
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useSelector } from "react-redux";

type Props = {
   id: string
   isActive: boolean
   title: string
   desc: string
   status: number
   createdAt: string
}

type PropsKomentar = {
   id: string
   comment: string
   createdAt: string
   idUser: string
   img: string
   username: string
   isEdited: boolean
   updatedAt: string
}

export default function DetailDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const entities = useSelector((state: any) => state.entities)
   const { id } = useLocalSearchParams<{ id: string }>();
   const [data, setData] = useState<Props>()
   const [dataKomentar, setDataKomentar] = useState<PropsKomentar[]>([])
   const [memberDiscussion, setMemberDiscussion] = useState(false)
   const [komentar, setKomentar] = useState('')
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [loading, setLoading] = useState(true)
   const [loadingKomentar, setLoadingKomentar] = useState(true)
   const arrSkeleton = Array.from({ length: 3 }, (_, index) => index)
   const reference = ref(getDB(), `/discussion-general/${id}`);
   const headerHeight = useHeaderHeight();
   const [detailMore, setDetailMore] = useState<any>([])
   const [loadingSendKomentar, setLoadingSendKomentar] = useState(false)
   const [isVisible, setVisible] = useState(false)
   const [selectKomentar, setSelectKomentar] = useState({
      id: '',
      comment: ''
   })
   const [viewEdit, setViewEdit] = useState(false)



   useEffect(() => {
      const onValueChange = reference.on('value', snapshot => {
         if (snapshot.val() == null) {
            reference.set({ trigger: true })
         }
         handleLoad('komentar', false)
      });

      // Stop listening for updates when no longer required
      return () => reference.off('value', onValueChange);
   }, []);

   function updateTrigger() {
      reference.once('value', snapshot => {
         const data = snapshot.val();
         reference.update({ trigger: !data.trigger });
      });
   }


   async function handleLoad(cat: 'detail' | 'komentar' | 'cek-anggota', loading: boolean) {
      try {
         if (cat == "detail") {
            setLoading(loading)
         } else if (cat == "komentar") {
            setLoadingKomentar(loading)
         }

         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDiscussionGeneralOne({ id: id, user: hasil, cat })

         if (cat == 'detail') {
            setData(response.data)
         } else if (cat == 'komentar') {
            setDataKomentar(response.data)
         } else if (cat == 'cek-anggota') {
            setMemberDiscussion(response.data)
         }

      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
         setLoadingKomentar(false)
      }
   }

   useEffect(() => {
      handleLoad('detail', false)
      handleLoad('komentar', false)
      handleLoad('cek-anggota', false)
   }, [update]);

   useEffect(() => {
      handleLoad('detail', true)
      handleLoad('komentar', true)
      handleLoad('cek-anggota', true)
   }, []);

   async function handleKomentar() {
      try {
         setLoadingSendKomentar(true)
         if (komentar != '') {
            const hasil = await decryptToken(String(token?.current))
            const response = await apiSendDiscussionGeneralCommentar({ id: id, data: { desc: komentar, user: hasil } })
            if (response.success) {
               setKomentar('')
               updateTrigger()
            } else {
               Toast.show({ type: 'small', text1: response.message })
            }
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoadingSendKomentar(false)
      }
   }

   async function handleEditKomentar() {
      try {
         setLoadingSendKomentar(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiUpdateDiscussionGeneralCommentar({ id: selectKomentar.id, data: { desc: selectKomentar.comment, user: hasil } })
         if (response.success) {
            updateTrigger()
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoadingSendKomentar(false)
         handleViewEditKomentar()
      }
   }

   async function handleDeleteKomentar() {
      try {
         setLoadingSendKomentar(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteDiscussionGeneralCommentar({ id: selectKomentar.id, data: { user: hasil } })
         if (response.success) {
            updateTrigger()
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoadingSendKomentar(false)
         setVisible(false)
      }
   }

   function handleMenuKomentar(id: string, comment: string) {
      setSelectKomentar({ id, comment })
      setVisible(true)
   }

   function handleViewEditKomentar() {
      setVisible(false)
      setViewEdit(!viewEdit)
   }

   return (
      <>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Diskusi',
               headerTitleAlign: 'center',
               headerRight: () => <HeaderRightDiscussionGeneralDetail id={id} active={data?.isActive !== undefined ? data.isActive : false} status={data?.status !== undefined ? data.status : 0} />,
            }}
         />
         <View style={{ flex: 1 }}>
            <ScrollView showsVerticalScrollIndicator={false}>
               <View style={[Styles.p15, Styles.mb100]}>
                  {
                     loading ?
                        <SkeletonContent />
                        :
                        <BorderBottomItem
                           descEllipsize={false}
                           borderType="bottom"
                           icon={
                              <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                                 <MaterialIcons name="chat" size={25} color={'#384288'} />
                              </View>
                           }
                           title={data?.title}
                           titleShowAll={true}
                           subtitle={
                              !data?.isActive ?
                                 <LabelStatus category='warning' text='ARSIP' size="small" />
                                 :
                                 <LabelStatus category={data.status == 1 ? 'success' : 'error'} text={data.status == 1 ? 'BUKA' : 'TUTUP'} size="small" />
                           }
                           desc={data?.desc}
                           leftBottomInfo={
                              <View style={[Styles.rowItemsCenter]}>
                                 <Ionicons name="chatbox-ellipses-outline" size={18} color="grey" style={Styles.mr05} />
                                 <Text style={[Styles.textInformation, Styles.cGray, Styles.mb05]}>{dataKomentar.length} Komentar</Text>
                              </View>
                           }
                           rightBottomInfo={
                              <View style={[Styles.rowItemsCenter]}>
                                 <Text style={[Styles.textInformation, Styles.cGray, Styles.mb05]}>{data?.createdAt}</Text>
                              </View>
                           }
                        />
                  }
                  <View style={[Styles.p15]}>
                     {
                        loadingKomentar ?
                           arrSkeleton.map((item: any, i: number) => {
                              return (
                                 <Skeleton key={i} width={100} widthType="percent" height={40} borderRadius={5} />
                              )
                           })
                           :
                           dataKomentar.map((item, i) => {
                              return (
                                 <BorderBottomItem
                                    key={i}
                                    borderType="bottom"
                                    colorPress
                                    icon={
                                       <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                                    }
                                    title={item.username}
                                    rightTopInfo={item.createdAt}
                                    desc={item.comment}
                                    rightBottomInfo={item.isEdited ? "Edited" : ""}
                                    descEllipsize={detailMore.includes(item.id) ? false : true}
                                    onPress={() => {
                                       setDetailMore((prev: any) => {
                                          if (prev.includes(item.id)) {
                                             return prev.filter((id: string) => id !== item.id)
                                          } else {
                                             return [...prev, item.id]
                                          }
                                       })
                                    }}
                                    onLongPress={() => {
                                       item.idUser == entities.id && data?.status != 2 && data?.isActive && handleMenuKomentar(item.id, item.comment)
                                    }}
                                 />
                              )
                           })
                     }
                  </View>
               </View>
            </ScrollView>
            <KeyboardAvoidingView
               behavior={Platform.OS === 'ios' ? 'padding' : undefined}
               keyboardVerticalOffset={headerHeight}
            >
               <View style={[
                  Styles.contentItemCenter,
                  Styles.w100,
                  { backgroundColor: "#f4f4f4" },
                  viewEdit && Styles.borderTop
               ]}>
                  {
                     viewEdit ?
                        <>
                           <View style={[Styles.w90, Styles.rowSpaceBetween, Styles.pv05]}>
                              <View style={[Styles.rowItemsCenter]}>
                                 <Feather name="edit-3" color="black" size={22} style={[Styles.mh05]} />
                                 <Text style={[Styles.textMediumSemiBold]}>Edit Komentar</Text>
                              </View>
                              <Pressable onPress={() => handleViewEditKomentar()}>
                                 <MaterialIcons name="close" color="black" size={22} />
                              </Pressable>
                           </View>
                           <InputForm
                              disable={(data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin")))}
                              type="default"
                              round
                              placeholder="Kirim Komentar"
                              bg="white"
                              onChange={(val: string) => setSelectKomentar({ ...selectKomentar, comment: val })}
                              value={selectKomentar.comment}
                              multiline
                              focus={viewEdit}
                              itemRight={
                                 <Pressable onPress={() => {
                                    (!loadingSendKomentar && selectKomentar.comment != '' && !regexOnlySpacesOrEnter.test(selectKomentar.comment) && data?.status === 1 && data?.isActive && (memberDiscussion || (entityUser.role != "user" && entityUser.role != "coadmin")))
                                       && handleEditKomentar()
                                 }}
                                    style={[
                                       Platform.OS == 'android' && Styles.mb12,
                                    ]}
                                 >
                                    <MaterialIcons name="send" size={25} style={(loadingSendKomentar || selectKomentar.comment == '' || regexOnlySpacesOrEnter.test(selectKomentar.comment) || data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin"))) ? Styles.cGray : Styles.cDefault} />
                                 </Pressable>
                              }
                           />
                        </>
                        :
                        data?.status != 2 && data?.isActive && ((entityUser.role != "user" && entityUser.role != "coadmin") || memberDiscussion)
                           ?
                           <InputForm
                              disable={(data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin")))}
                              type="default"
                              round
                              placeholder="Kirim Komentar"
                              bg="white"
                              onChange={setKomentar}
                              value={komentar}
                              multiline
                              focus={viewEdit}
                              itemRight={
                                 <Pressable onPress={() => {
                                    (!loadingSendKomentar && komentar != '' && !regexOnlySpacesOrEnter.test(komentar) && data?.status === 1 && data?.isActive && (memberDiscussion || (entityUser.role != "user" && entityUser.role != "coadmin")))
                                       && handleKomentar()
                                 }}
                                    style={[
                                       Platform.OS == 'android' && Styles.mb12,
                                    ]}
                                 >
                                    <MaterialIcons name="send" size={25} style={(loadingSendKomentar || komentar == '' || regexOnlySpacesOrEnter.test(komentar) || data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin"))) ? Styles.cGray : Styles.cDefault} />
                                 </Pressable>
                              }
                           />
                           :
                           <View style={[Styles.pv20, { alignItems: 'center' }]}>
                              <Text style={[Styles.textInformation, Styles.cGray]}>
                                 {
                                    data?.status == 2 ? "Diskusi telah ditutup" : data?.isActive == false ? "Diskusi telah diarsipkan" : "Hanya anggota diskusi yang dapat memberikan komentar"
                                 }
                              </Text>
                           </View>
                  }

               </View>
            </KeyboardAvoidingView>
         </View >

         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Komentar">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="pencil-outline" color="black" size={25} />}
                  title="Edit"
                  onPress={() => { handleViewEditKomentar() }}
               />
               <MenuItemRow
                  icon={<MaterialIcons name="delete" color="black" size={25} />}
                  title="Hapus"
                  onPress={() => {
                     AlertKonfirmasi({
                        title: 'Konfirmasi',
                        desc: 'Apakah anda yakin ingin menghapus komentar?',
                        onPress: () => {
                           handleDeleteKomentar()
                        }
                     })
                  }}
               />
            </View>
         </DrawerBottom>
      </>
   )
}