import AppHeader from "@/components/AppHeader";
import BorderBottomItem from "@/components/borderBottomItem";
import BorderBottomItem2 from "@/components/borderBottomItem2";
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 ModalConfirmation from "@/components/ModalConfirmation";
import Skeleton from "@/components/skeleton";
import SkeletonContent from "@/components/skeletonContent";
import Text from '@/components/Text';
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 { useTheme } from "@/providers/ThemeProvider";
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 React, { useEffect, useState } from "react";
import { KeyboardAvoidingView, Platform, Pressable, RefreshControl, 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
}

type PropsFile = {
   id: string;
   idStorage: string;
   name: string;
   extension: string
}

export default function DetailDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   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 [fileDiscussion, setFileDiscussion] = useState<PropsFile[]>([])
   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 [refreshing, setRefreshing] = useState(false)
   const [selectKomentar, setSelectKomentar] = useState({
      id: '',
      comment: ''
   })
   const [viewEdit, setViewEdit] = useState(false)
   const [showDeleteModal, setShowDeleteModal] = 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' | 'file', 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)
         } else if (cat == 'file') {
            setFileDiscussion(response.data)
         }

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

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

   useEffect(() => {
      handleLoad('detail', true)
      handleLoad('komentar', true)
      handleLoad('cek-anggota', true)
      handleLoad('file', 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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menambahkan data"

         Toast.show({ type: 'small', text1: message })
      } 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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengupdate data"

         Toast.show({ type: 'small', text1: message })
      } 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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menghapus data"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setLoadingSendKomentar(false)
         setVisible(false)
      }
   }

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

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

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad('detail', false)
      handleLoad('komentar', false)
      handleLoad('cek-anggota', false)
      handleLoad('file', false)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   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} />,
               header: () => (
                  <AppHeader
                     title="Diskusi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightDiscussionGeneralDetail id={id} active={data?.isActive !== undefined ? data.isActive : false} status={data?.status !== undefined ? data.status : 0} />}
                  />
               )
            }}
         />
         <View style={[Styles.flex1, { backgroundColor: colors.background }]}>
            <ScrollView
               showsVerticalScrollIndicator={false}
               style={[Styles.h100, { backgroundColor: colors.background }]}
               refreshControl={
                  <RefreshControl
                     refreshing={refreshing}
                     onRefresh={() => handleRefresh()}
                     tintColor={colors.icon}
                  />
               }
            >
               <View style={[Styles.p15]}>
                  {
                     loading ?
                        <SkeletonContent />
                        :
                        <BorderBottomItem2
                           dataFile={fileDiscussion}
                           descEllipsize={false}
                           borderType="all"
                           bgColor="white"
                           icon={
                              <View style={[Styles.iconContent]}>
                                 <MaterialIcons name="chat" size={25} color={'black'} />
                              </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={colors.dimmed} style={Styles.mr05} />
                                 <Text style={[Styles.textInformation, { color: colors.dimmed }, Styles.mb05]}>{dataKomentar.length} Komentar</Text>
                              </View>
                           }
                           rightBottomInfo={
                              <View style={[Styles.rowItemsCenter]}>
                                 <Text style={[Styles.textInformation, { color: colors.dimmed }, Styles.mb05]}>{data?.createdAt}</Text>
                              </View>
                           }
                        />
                  }
                  <View style={[Styles.mt10]}>
                     {
                        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="all"
                                    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}
                                    bgColor="white"
                                    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: colors.background },
                  viewEdit && Styles.borderTop
               ]}>
                  {
                     viewEdit ?
                        <>
                           <View style={[Styles.w90, Styles.rowSpaceBetween, Styles.pv05]}>
                              <View style={[Styles.rowItemsCenter]}>
                                 <Feather name="edit-3" color={colors.text} size={22} style={[Styles.mh05]} />
                                 <Text style={[Styles.textMediumSemiBold]}>Edit Komentar</Text>
                              </View>
                              <Pressable onPress={() => handleViewEditKomentar()}>
                                 <MaterialIcons name="close" color={colors.text} size={22} />
                              </Pressable>
                           </View>
                           <InputForm
                              disable={(data?.status === 2 || !data?.isActive || (!memberDiscussion && (entityUser.role == "user" || entityUser.role == "coadmin")))}
                              type="default"
                              round
                              placeholder="Kirim Komentar"
                              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"))) ? { color: colors.dimmed } : { color: colors.tint }} />
                                 </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"
                              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"))) ? { color: colors.dimmed } : { color: colors.tint }} />
                                 </Pressable>
                              }
                           />
                           :
                           <View style={[Styles.pv20, Styles.itemsCenter]}>
                              <Text style={[Styles.textInformation, { color: colors.dimmed }]}>
                                 {
                                    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={colors.text} size={25} />}
                  title="Edit"
                  onPress={() => { handleViewEditKomentar() }}
               />
               <MenuItemRow
                  icon={<Ionicons name="trash-outline" color={colors.text} size={25} />}
                  title="Hapus"
                  onPress={() => {
                     setVisible(false)
                     setTimeout(() => {
                        setShowDeleteModal(true)
                     }, 600)
                  }}
               />
            </View>
         </DrawerBottom>

         <ModalConfirmation
            visible={showDeleteModal}
            title="Konfirmasi"
            message="Apakah anda yakin ingin menghapus komentar?"
            onConfirm={() => {
               setShowDeleteModal(false)
               handleDeleteKomentar()
            }}
            onCancel={() => setShowDeleteModal(false)}
            confirmText="Hapus"
            cancelText="Batal"
         />
      </>
   )
}