import GuideOverlay from "@/components/GuideOverlay";
import ButtonTab from "@/components/buttonTab";
import ImageUser from "@/components/imageNew";
import InputSearch from "@/components/inputSearch";
import SkeletonContent from "@/components/skeletonContent";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetDiscussion, apiGetDivisionOneFeature } from "@/lib/api";
import { GUIDE_DIVISION_DISCUSSION } from "@/lib/guideSteps";
import { useGuide } from "@/lib/useGuide";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { FlatList, Pressable, RefreshControl, View } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string,
   title: string,
   desc: string,
   status: number,
   user_name: string,
   img: string,
   total_komentar: number,
   createdAt: string,
   isActive: boolean
}

export default function DiscussionDivision() {
   const { colors } = useTheme();
   const { id, active } = useLocalSearchParams<{ id: string, active?: string }>()
   const [data, setData] = useState<Props[]>([])
   const { token, decryptToken } = useAuthSession()
   const [search, setSearch] = useState('')
   const update = useSelector((state: any) => state.discussionUpdate)
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 })
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const [status, setStatus] = useState<'true' | 'false'>('true')
   const [refreshing, setRefreshing] = useState(false)
   const [isMemberDivision, setIsMemberDivision] = useState(false)
   const [isAdminDivision, setIsAdminDivision] = useState(false)
   const entityUser = useSelector((state: any) => state.user)
   const { visible: guideVisible, dismiss: dismissGuide } = useGuide('division-discussion')

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

   async function handleLoad(loading: boolean, thisPage: number) {
      try {
         setWaiting(true)
         setLoading(loading)
         setPage(thisPage)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDiscussion({ user: hasil, search, division: id, active: status, page: thisPage })
         if (thisPage == 1) {
            setData(response.data)
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data])
         }
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }

   useEffect(() => { handleLoad(false, 1) }, [update.data])
   useEffect(() => { handleLoad(true, 1) }, [status, search])
   useEffect(() => { handleCheckMember() }, [])

   const loadMoreData = () => {
      if (waiting) return
      setTimeout(() => { handleLoad(false, page + 1) }, 1000);
   }

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad(false, 1)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   const isOpen = (item: Props) => item.status === 1

   const themed = {
      background:       { backgroundColor: colors.background },
      card:             { backgroundColor: colors.card, borderColor: colors.icon + '20' },
      cardPressed:      { backgroundColor: colors.icon + '10' },
      title:            { color: colors.text },
      dimmed:           { color: colors.dimmed },
      statusOpen:       { borderColor: '#10B981' as const },
      statusClosed:     { borderColor: colors.dimmed + '80' },
      statusTextOpen:   { color: '#10B981' as const },
      statusTextClosed: { color: colors.dimmed },
   }

   return (
      <View style={[Styles.flex1, themed.background]}>
         <GuideOverlay visible={guideVisible} steps={GUIDE_DIVISION_DISCUSSION} onDismiss={dismissGuide} />
         {((entityUser.role != "user" && entityUser.role != "coadmin") || isAdminDivision) && (
            <View style={[Styles.ph15, Styles.discussionHeaderPadding]}>
               <WrapTab>
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="true"
                     onPress={() => setStatus("true")}
                     label="Aktif"
                     icon={<Feather name="check-circle" color={status == "false" ? colors.dimmed : 'white'} size={20} />}
                     n={2}
                  />
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="false"
                     onPress={() => setStatus("false")}
                     label="Arsip"
                     icon={<AntDesign name="closecircleo" color={status == "true" ? colors.dimmed : 'white'} size={20} />}
                     n={2}
                  />
               </WrapTab>
               <InputSearch onChange={setSearch} />
            </View>
         )}

         <View style={[Styles.flex1, Styles.ph15, Styles.discussionListPadding]}>
            {loading ? (
               arrSkeleton.map((_, i) => <SkeletonContent key={i} />)
            ) : data.length === 0 ? (
               <View style={[Styles.contentItemCenter, Styles.mt30]}>
                  <Feather name="message-circle" size={42} color={colors.icon + '40'} />
                  <Text style={[Styles.mt10, Styles.discussionEmptyText, themed.dimmed]}>
                     Tidak ada diskusi
                  </Text>
               </View>
            ) : (
               <FlatList
                  data={data}
                  keyExtractor={(_, i) => String(i)}
                  showsVerticalScrollIndicator={false}
                  onEndReached={loadMoreData}
                  onEndReachedThreshold={0.5}
                  refreshControl={
                     <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} tintColor={colors.icon} />
                  }
                  ItemSeparatorComponent={() => <View style={Styles.discussionSeparator} />}
                  renderItem={({ item }: { item: Props }) => (
                     <Pressable
                        onPress={() => router.push(`./discussion/${item.id}`)}
                        style={({ pressed }) => [
                           Styles.discussionCard,
                           themed.card,
                           pressed && themed.cardPressed,
                        ]}
                     >
                        <View style={[Styles.rowItemsCenter, Styles.mb08]}>
                           <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} size="xs" />
                           <View style={[Styles.flex1, Styles.discussionTitleCol]}>
                              <Text style={[Styles.textDefaultSemiBold, themed.title]} numberOfLines={1}>
                                 {item.user_name}
                              </Text>
                              {status === "true" && (
                                 <View style={[Styles.discussionStatusPill, isOpen(item) ? themed.statusOpen : themed.statusClosed]}>
                                    <Text style={[Styles.discussionStatusText, isOpen(item) ? themed.statusTextOpen : themed.statusTextClosed]}>
                                       {isOpen(item) ? 'Buka' : 'Tutup'}
                                    </Text>
                                 </View>
                              )}
                           </View>
                        </View>

                        {item.desc ? (
                           <Text style={[Styles.textMediumNormal, Styles.discussionCardIndent, Styles.discussionDescMargin, themed.title]} numberOfLines={2}>
                              {item.desc}
                           </Text>
                        ) : null}

                        <View style={[Styles.rowItemsCenter, Styles.rowSpaceBetween, Styles.discussionCardIndent]}>
                           <View style={Styles.rowItemsCenter}>
                              <Feather name="message-square" size={14} color={colors.dimmed} />
                              <Text style={[Styles.discussionCommentText, themed.dimmed]}>
                                 {item.total_komentar} Komentar
                              </Text>
                           </View>
                           <Text style={[Styles.discussionDateText, themed.dimmed]}>
                              {item.createdAt}
                           </Text>
                        </View>
                     </Pressable>
                  )}
               />
            )}
         </View>
      </View>
   );
}
