import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import HeaderRightDiscussionGeneralDetail from "@/components/discussion_general/headerDiscussionDetail";
import ImageUser from "@/components/imageNew";
import { InputForm } from "@/components/inputForm";
import LabelStatus from "@/components/labelStatus";
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 Styles from "@/constants/Styles";
import { apiGetDiscussionGeneralOne, apiSendDiscussionGeneralCommentar } from "@/lib/api";
import { getDB } from "@/lib/firebaseDatabase";
import { useAuthSession } from "@/providers/AuthProvider";
import { Ionicons, 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 { 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
}

export default function DetailDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   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();

   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 {
         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()
            }
         }
      } catch (error) {
         console.error(error)
      }
   }

   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}
                           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" />
                           }
                           rightTopInfo={data?.createdAt}
                           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>
                           }
                        />
                  }
                  <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"
                                    icon={
                                       <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                                    }
                                    title={item.username}
                                    rightTopInfo={item.createdAt}
                                    desc={item.comment}
                                 />
                              )
                           })
                     }
                  </View>
               </View>
            </ScrollView>
            <KeyboardAvoidingView
               behavior={Platform.OS === 'ios' ? 'padding' : undefined}
               keyboardVerticalOffset={headerHeight}
            >
               <View style={[
                  Styles.contentItemCenter,
                  Styles.w100,
                  { backgroundColor: "#f4f4f4" },
               ]}>
                  <InputForm
                     disable={(data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin")))}
                     type="default"
                     round
                     placeholder="Kirim Komentar2"
                     bg="white"
                     onChange={setKomentar}
                     value={komentar}
                     multiline
                     itemRight={
                        <Pressable onPress={() => {
                           (komentar != '' && data?.status === 1 && data?.isActive && (memberDiscussion || (entityUser.role != "user" && entityUser.role != "coadmin")))
                              && handleKomentar()
                        }}>
                           <MaterialIcons name="send" size={25} style={(komentar == '' || data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin"))) ? Styles.cGray : Styles.cDefault} />
                        </Pressable>
                     }
                  />
               </View>
            </KeyboardAvoidingView>
         </View >
      </>
   )
}