import BorderBottomItem from "@/components/borderBottomItem";
import ButtonBackHeader from "@/components/buttonBackHeader";
import HeaderRightDiscussionDetail from "@/components/discussion/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 Styles from "@/constants/Styles";
import {
   apiGetDiscussionOne,
   apiGetDivisionOneFeature,
   apiSendDiscussionCommentar,
} 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, RefreshControl, ScrollView, View } from "react-native";
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;
};

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();


   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);
      }
   }


   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={`https://wibu-storage.wibudev.com/api/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"
                                 icon={
                                    <ImageUser
                                       src={`https://wibu-storage.wibudev.com/api/files/${item.img}`}
                                       size="xs"
                                    />
                                 }
                                 title={item.username}
                                 rightTopInfo={item.createdAt}
                                 desc={item.comment}
                                 descEllipsize={false}
                              />
                           ))
                     }

                  </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 == false ||
                        ((entityUser.role == "user" || entityUser.role == "coadmin") &&
                           !isMemberDivision)
                     }
                     bg="white"
                     type="default"
                     round
                     placeholder="Kirim Komentar"
                     onChange={setKomentar}
                     value={komentar}
                     itemRight={
                        <Pressable
                           onPress={() => {
                              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();
                           }}
                        >
                           <MaterialIcons
                              name="send"
                              size={25}
                              style={
                                 komentar == "" ||
                                    loadingSend ||
                                    data?.status == 2 ||
                                    data?.isActive == false ||
                                    ((entityUser.role == "user" ||
                                       entityUser.role == "coadmin") &&
                                       !isMemberDivision)
                                    ? Styles.cGray
                                    : Styles.cDefault
                              }
                           />
                        </Pressable>
                     }
                  />
               </View>
            </KeyboardAvoidingView>

         </View>
      </>
   );
}
