import AppHeader from "@/components/AppHeader";
import BorderBottomItem2 from "@/components/borderBottomItem2";
import DiscussionCommentInput from "@/components/discussion_general/discussionCommentInput";
import DiscussionCommentList, { CommentFile, CommentItem } from "@/components/discussion_general/discussionCommentList";
import HeaderRightDiscussionGeneralDetail from "@/components/discussion_general/headerDiscussionDetail";
import DrawerBottom from "@/components/drawerBottom";
import MenuItemRow from "@/components/menuItemRow";
import ModalConfirmation from "@/components/ModalConfirmation";
import SkeletonContent from "@/components/skeletonContent";
import Text from '@/components/Text';
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiDeleteDiscussionGeneralCommentar, apiGetDiscussionGeneralOne, apiSendDiscussionGeneralCommentar, apiSendDiscussionGeneralCommentarWithFile, apiUpdateDiscussionGeneralCommentar } from "@/lib/api";
import { getDB } from "@/lib/firebaseDatabase";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Feather, Ionicons, MaterialCommunityIcons } 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, RefreshControl, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useSelector } from "react-redux";

type DiscussionDetail = {
   id: string; isActive: boolean; title: string
   desc: string; status: number; createdAt: 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<DiscussionDetail>()
   const [dataKomentar, setDataKomentar] = useState<CommentItem[]>([])
   const [memberDiscussion, setMemberDiscussion] = useState(false)
   const [fileDiscussion, setFileDiscussion] = useState<PropsFile[]>([])
   const [komentar, setKomentar] = useState('')
   const [commentFiles, setCommentFiles] = useState<{ uri: string; name: string }[]>([])
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [loading, setLoading] = useState(true)
   const [loadingKomentar, setLoadingKomentar] = useState(true)
   const [loadingSend, setLoadingSend] = useState(false)
   const [isVisible, setVisible] = useState(false)
   const [refreshing, setRefreshing] = useState(false)
   const [selectKomentar, setSelectKomentar] = useState<{ id: string; comment: string; files: CommentFile[] }>({ id: '', comment: '', files: [] })
   const [removedFileIds, setRemovedFileIds] = useState<string[]>([])
   const [viewEdit, setViewEdit] = useState(false)
   const [showDeleteModal, setShowDeleteModal] = useState(false)
   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)
      })
      return () => reference.off('value', onValueChange)
   }, [])

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

   async function handleLoad(cat: 'detail' | 'komentar' | 'cek-anggota' | 'file', showLoading: boolean) {
      try {
         if (cat === 'detail') setLoading(showLoading)
         else if (cat === 'komentar') setLoadingKomentar(showLoading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDiscussionGeneralOne({ 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', true); handleLoad('komentar', true)
      handleLoad('cek-anggota', true); handleLoad('file', true)
   }, [])

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

   async function handleKomentar() {
      try {
         setLoadingSend(true)
         const hasil = await decryptToken(String(token?.current))
         let response
         if (commentFiles.length > 0) {
            const fd = new FormData()
            commentFiles.forEach((f, i) =>
               fd.append(`file${i}`, { uri: f.uri, type: 'application/octet-stream', name: f.name } as any)
            )
            fd.append("data", JSON.stringify({ desc: komentar, user: hasil }))
            response = await apiSendDiscussionGeneralCommentarWithFile(id, fd)
         } else {
            response = await apiSendDiscussionGeneralCommentar({ id, data: { desc: komentar, user: hasil } })
         }
         if (response.success) {
            setKomentar(''); setCommentFiles([])
            updateTrigger()
         } else {
            Toast.show({ type: 'small', text1: response.message })
         }
      } catch (error: any) {
         Toast.show({ type: 'small', text1: error?.response?.data?.message || "Gagal menambahkan data" })
      } finally { setLoadingSend(false) }
   }

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

   async function handleDeleteKomentar() {
      try {
         setLoadingSend(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) {
         Toast.show({ type: 'small', text1: error?.response?.data?.message || "Gagal menghapus data" })
      } finally { setLoadingSend(false); setVisible(false) }
   }

   function handleViewEditKomentar() { setVisible(false); setViewEdit(!viewEdit); setRemovedFileIds([]) }

   const isLocked = data?.status === 2 || !data?.isActive
   const isMember = memberDiscussion || (entityUser.role !== "user" && entityUser.role !== "coadmin")
   const canComment = !isLocked && isMember

   function lockedReason() {
      if (data?.status === 2) return "Diskusi telah ditutup"
      if (!data?.isActive) return "Diskusi telah diarsipkan"
      return "Hanya anggota diskusi yang dapat memberikan komentar"
   }

   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={{
               header: () => (
                  <AppHeader
                     title="Diskusi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightDiscussionGeneralDetail id={id} active={data?.isActive ?? false} status={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.discussionIconCircleLg, { backgroundColor: colors.icon + '20' }]}>
                              <Feather name="message-circle" size={22} color={colors.icon} />
                           </View>
                        }
                        title={data?.title}
                        titleShowAll={true}
                        subtitle={
                           <View style={[Styles.discussionStatusPill, {
                              borderColor: !data?.isActive ? '#F59E0B' : data?.status === 1 ? '#10B981' : colors.dimmed + '80'
                           }]}>
                              <Text style={[Styles.discussionStatusText, {
                                 color: !data?.isActive ? '#F59E0B' : data?.status === 1 ? '#10B981' : colors.dimmed
                              }]}>
                                 {!data?.isActive ? 'Arsip' : data?.status === 1 ? 'Buka' : 'Tutup'}
                              </Text>
                           </View>
                        }
                        desc={data?.desc}
                        leftBottomInfo={
                           <View style={Styles.rowItemsCenter}>
                              <Feather name="message-square" size={14} color={colors.dimmed} style={Styles.mr05} />
                              <Text style={[Styles.textInformation, { color: colors.dimmed }]}>{dataKomentar.length} Komentar</Text>
                           </View>
                        }
                        rightBottomInfo={<Text style={[Styles.textInformation, { color: colors.dimmed }]}>{data?.createdAt}</Text>}
                     />
                  )}
                  <DiscussionCommentList
                     data={dataKomentar}
                     loading={loadingKomentar}
                     myId={entities.id}
                     canInteract={data?.status !== 2 && data?.isActive === true}
                     onLongPress={(commentId, comment, files) => {
                        setSelectKomentar({ id: commentId, comment, files })
                        setRemovedFileIds([])
                        setVisible(true)
                     }}
                  />
               </View>
            </ScrollView>

            <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={headerHeight}>
               {canComment ? (
                  <DiscussionCommentInput
                     mode={viewEdit ? 'edit' : 'new'}
                     value={viewEdit ? selectKomentar.comment : komentar}
                     onChange={viewEdit
                        ? (val) => setSelectKomentar({ ...selectKomentar, comment: val })
                        : setKomentar
                     }
                     loading={loadingSend}
                     onSend={viewEdit ? handleEditKomentar : handleKomentar}
                     onCancelEdit={handleViewEditKomentar}
                     files={viewEdit ? [] : commentFiles}
                     onAddFile={viewEdit ? undefined : (newFiles) => setCommentFiles(prev => [...prev, ...newFiles])}
                     onRemoveFile={viewEdit ? undefined : (idx) => setCommentFiles(prev => prev.filter((_, i) => i !== idx))}
                     existingFiles={viewEdit ? selectKomentar.files.filter(f => !removedFileIds.includes(f.id)) : []}
                     onRemoveExistingFile={viewEdit ? (fileId) => setRemovedFileIds(prev => prev.includes(fileId) ? prev.filter(id => id !== fileId) : [...prev, fileId]) : undefined}
                     canSend={canComment}
                  />
               ) : (
                  <DiscussionCommentInput
                     mode="locked"
                     lockedReason={lockedReason()}
                     value="" onChange={() => {}} loading={false} onSend={() => {}} canSend={false}
                  />
               )}
            </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"
         />
      </>
   )
}
