import AlertKonfirmasi from "@/components/alertKonfirmasi";
import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import HeaderRightDiscussionDetail from "@/components/discussion/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 { ConstEnv } from "@/constants/ConstEnv";
import { regexOnlySpacesOrEnter } from "@/constants/OnlySpaceOrEnter";
import Styles from "@/constants/Styles";
import {
   apiDeleteDiscussionCommentar,
   apiEditDiscussionCommentar,
   apiGetDiscussionOne,
   apiGetDivisionOneFeature,
   apiSendDiscussionCommentar,
} 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, RefreshControl, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useSelector } from "react-redux";

type Props = {
   id: string;
   title: string;
   desc: string;
   status: number;
   createdAt: string;
   createdBy: string;
   username: string;
   user_img: string;
   isCreator: boolean;
   isActive: boolean;
};

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

export default function DiscussionDetail() {
   const { id, detail } = useLocalSearchParams<{ id: string; detail: string }>();
   const [data, setData] = useState<Props>();
   const [dataComment, setDataComment] = useState<PropsComment[]>([]);
   const { token, decryptToken } = useAuthSession();
   const [komentar, setKomentar] = useState("");
   const [loadingSend, setLoadingSend] = useState(false);
   const update = useSelector((state: any) => state.discussionUpdate);
   const entityUser = useSelector((state: any) => state.user);
   const [isMemberDivision, setIsMemberDivision] = useState(false);
   const [isAdminDivision, setIsAdminDivision] = useState(false);
   const [isCreator, setIsCreator] = useState(false);
   const [loading, setLoading] = useState(true)
   const [loadingKomentar, setLoadingKomentar] = useState(true)
   const arrSkeleton = Array.from({ length: 3 })
   const reference = ref(getDB(), `/discussion-division/${detail}`);
   const [refreshing, setRefreshing] = useState(false)
   const headerHeight = useHeaderHeight();
   const [detailMore, setDetailMore] = useState<any>([])
   const entities = useSelector((state: any) => state.entities)
   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 })
         }
         handleLoadComment(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(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDiscussionOne({
            id: detail,
            user: hasil,
            cat: "data",
         });
         setData(response.data);
         setIsCreator(response.data.createdBy == hasil);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

   async function handleLoadComment(loading: boolean) {
      try {
         setLoadingKomentar(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDiscussionOne({
            id: detail,
            user: hasil,
            cat: "comment",
         });
         setDataComment(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoadingKomentar(false)
      }
   }

   async function handleCheckMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-member",
         });

         const response2 = await apiGetDivisionOneFeature({
            id,
            user: hasil,
            cat: "check-admin",
         });
         setIsMemberDivision(response.data);
         setIsAdminDivision(response2.data);
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleLoad(false);
   }, [update.data]);

   useEffect(() => {
      handleLoad(true)
      handleLoadComment(true);
      handleCheckMember();
   }, []);

   async function handleKomentar() {
      try {
         setLoadingSend(true);
         const hasil = await decryptToken(String(token?.current));
         const response = await apiSendDiscussionCommentar({
            id: detail,
            data: { comment: komentar, user: hasil },
         });
         if (response.success) {
            setKomentar("")
            updateTrigger()
         }
      } catch (error) {
         console.error(error);
      } finally {
         setLoadingSend(false);
      }
   }

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

   async function handleDeleteKomentar() {
      try {
         setLoadingSend(true);
         const hasil = await decryptToken(String(token?.current));
         const response = await apiDeleteDiscussionCommentar({
            id: selectKomentar.id,
            data: { user: hasil },
         });
         if (response.success) {
            updateTrigger()
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error) {
         console.error(error);
      } finally {
         setLoadingSend(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(false)
      handleLoadComment(false)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   return (
      <>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Diskusi",
               headerTitleAlign: "center",
               headerRight: () =>
                  (entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision || isCreator ?
                     <HeaderRightDiscussionDetail
                        id={detail}
                        status={data?.status}
                        isActive={data?.isActive}
                     /> : (<></>)
               ,
            }}
         />
         <View style={{ flex: 1 }}>
            <ScrollView
               refreshControl={
                  <RefreshControl
                     refreshing={refreshing}
                     onRefresh={handleRefresh}
                  />
               }
            >
               <View style={[Styles.p15, Styles.mb100]}>
                  {
                     loading ?
                        <SkeletonContent />
                        :
                        <BorderBottomItem
                           descEllipsize={false}
                           borderType="bottom"
                           icon={
                              <ImageUser
                                 src={`${ConstEnv.url_storage}/files/${data?.user_img}`}
                                 size="sm"
                              />
                           }
                           title={data?.username}
                           subtitle={
                              data?.isActive ? (
                                 data?.status == 1 ? (
                                    <LabelStatus category="success" text="BUKA" size="small" />
                                 ) : (
                                    <LabelStatus category="error" text="TUTUP" size="small" />
                                 )
                              ) : (
                                 <LabelStatus category="secondary" text="ARSIP" 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]} >
                                    {dataComment.length} Komentar
                                 </Text>
                              </View>
                           }
                        />
                  }

                  <View style={[Styles.p15]}>
                     {
                        loadingKomentar ?
                           arrSkeleton.map((item, index) => (
                              <Skeleton key={index} width={100} widthType="percent" height={40} borderRadius={5} />
                           ))
                           :
                           dataComment.map((item, index) => (
                              <BorderBottomItem
                                 key={index}
                                 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
                              bg="white"
                              type="default"
                              round
                              multiline
                              placeholder="Kirim Komentar"
                              onChange={(val: string) => setSelectKomentar({ ...selectKomentar, comment: val })}
                              value={selectKomentar.comment}
                              itemRight={
                                 <Pressable
                                    onPress={() => {
                                       selectKomentar.comment != "" &&
                                          !regexOnlySpacesOrEnter.test(selectKomentar.comment) &&
                                          !loadingSend &&
                                          data?.status != 2 &&
                                          data?.isActive &&
                                          (((entityUser.role == "user" ||
                                             entityUser.role == "coadmin") &&
                                             isMemberDivision) ||
                                             entityUser.role == "admin" ||
                                             entityUser.role == "supadmin" ||
                                             entityUser.role == "developer" ||
                                             entityUser.role == "cosupadmin") &&
                                          handleEditKomentar();
                                    }}
                                    style={[
                                       Platform.OS == 'android' && Styles.mb12,
                                    ]}
                                 >
                                    <MaterialIcons
                                       name="send"
                                       size={25}
                                       style={
                                          [selectKomentar.comment == "" || regexOnlySpacesOrEnter.test(selectKomentar.comment) || loadingSend || ((entityUser.role == "user" || entityUser.role == "coadmin") && !isMemberDivision)
                                             ? Styles.cGray
                                             : Styles.cDefault,
                                          ]
                                       }
                                    />
                                 </Pressable>
                              }
                           />
                        </>
                        :
                        data?.status != 2 && data?.isActive && ((entityUser.role != "user" && entityUser.role != "coadmin") ||
                           isMemberDivision)
                           ?
                           <InputForm
                              bg="white"
                              type="default"
                              round
                              multiline
                              placeholder="Kirim Komentar"
                              onChange={setKomentar}
                              value={komentar}
                              itemRight={
                                 <Pressable
                                    onPress={() => {
                                       komentar != "" &&
                                          !regexOnlySpacesOrEnter.test(komentar) &&
                                          !loadingSend &&
                                          data?.status != 2 &&
                                          data?.isActive &&
                                          (((entityUser.role == "user" ||
                                             entityUser.role == "coadmin") &&
                                             isMemberDivision) ||
                                             entityUser.role == "admin" ||
                                             entityUser.role == "supadmin" ||
                                             entityUser.role == "developer" ||
                                             entityUser.role == "cosupadmin") &&
                                          handleKomentar();
                                    }}
                                    style={[
                                       Platform.OS == 'android' && Styles.mb12,
                                    ]}
                                 >
                                    <MaterialIcons
                                       name="send"
                                       size={25}
                                       style={
                                          [komentar == "" || regexOnlySpacesOrEnter.test(komentar) || loadingSend || ((entityUser.role == "user" || entityUser.role == "coadmin") && !isMemberDivision)
                                             ? 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 divisi 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>
      </>
   );
}
