import GuideOverlay from "@/components/GuideOverlay";
import ModalConfirmation from "@/components/ModalConfirmation";
import BorderBottomItem from "@/components/borderBottomItem";
import { ButtonForm } from "@/components/buttonForm";
import ButtonTab from "@/components/buttonTab";
import DrawerBottom from "@/components/drawerBottom";
import { InputForm } from "@/components/inputForm";
import InputSearch from "@/components/inputSearch";
import MenuItemRow from "@/components/menuItemRow";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import Styles from "@/constants/Styles";
import { apiDeleteGroup, apiEditGroup, apiGetGroup } from "@/lib/api";
import { setUpdateGroup } from "@/lib/groupSlice";
import { GUIDE_GROUP } from "@/lib/guideSteps";
import { useGuide } from "@/lib/useGuide";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather, Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react";
import { RefreshControl, View, VirtualizedList } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

type Props = {
   id: string
   name: string
   isActive: boolean
}

export default function Index() {
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const [isModal, setModal] = useState(false)
   const [isVisibleEdit, setVisibleEdit] = useState(false)
   const [search, setSearch] = useState('')
   const [showDeleteModal, setShowDeleteModal] = useState(false)
   const [status, setStatus] = useState<'true' | 'false'>('true')
   const [loadingSubmit, setLoadingSubmit] = useState(false)
   const [idChoose, setIdChoose] = useState('')
   const [activeChoose, setActiveChoose] = useState(true)
   const [titleChoose, setTitleChoose] = useState('')
   const queryClient = useQueryClient()
   const [refreshing, setRefreshing] = useState(false)
   const { visible: guideVisible, dismiss: dismissGuide } = useGuide('group')

   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.groupUpdate)
   const [error, setError] = useState({
      title: false,
   });

   // TanStack Query for Groups
   const {
      data: queryData,
      isLoading,
      refetch
   } = useQuery({
      queryKey: ['groups', { status, search }],
      queryFn: async () => {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetGroup({ 
            user: hasil, 
            active: status, 
            search: search 
         })
         return response;
      },
      enabled: !!token?.current,
      staleTime: 0,
   })

   const data = useMemo(() => queryData?.data || [], [queryData])

   useEffect(() => {
      refetch()
   }, [update, refetch])

   async function handleEdit() {
      try {
         setLoadingSubmit(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiEditGroup({ user: hasil, name: titleChoose }, idChoose)
         await queryClient.invalidateQueries({ queryKey: ['groups'] })
         dispatch(setUpdateGroup(!update))
      } catch (error) {
         console.error(error)
      } finally {
         setLoadingSubmit(false)
         setVisibleEdit(false)
         setModal(false)
         Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
      }

   }

   async function handleDelete() {
      try {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiDeleteGroup({ user: hasil, isActive: activeChoose }, idChoose)
         await queryClient.invalidateQueries({ queryKey: ['groups'] })
         dispatch(setUpdateGroup(!update))
      } catch (error) {
         console.error(error)
      } finally {
         setModal(false)
         Toast.show({ type: 'small', text1: 'Berhasil mengupdate data', })
      }
   }

   const handleRefresh = async () => {
      setRefreshing(true)
      await queryClient.invalidateQueries({ queryKey: ['groups'] })
      setRefreshing(false)
   };

   function validationForm(val: any, cat: 'title') {
      if (cat === 'title') {
         setTitleChoose(val)
         if (val == "" || val.length < 3) {
            setError((prev) => ({ ...prev, title: true }))
         } else {
            setError((prev) => ({ ...prev, title: false }))
         }
      }
   }


   const getItem = (_data: unknown, index: number): Props => ({
      id: data[index].id,
      name: data[index].name,
      isActive: data[index].isActive,
   });



   const arrSkeleton = [0, 1, 2, 3, 4]

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         <GuideOverlay visible={guideVisible} steps={GUIDE_GROUP} onDismiss={dismissGuide} />
         <View style={[Styles.mb10]}>
            <WrapTab>
               <ButtonTab
                  active={status == "false" ? "false" : "true"}
                  value="true"
                  onPress={() => { setStatus("true") }}
                  label="Aktif"
                  icon={<Feather name="check-circle" color={status == "true" ? 'white' : colors.dimmed} size={20} />}
                  n={2} />
               <ButtonTab
                  active={status == "false" ? "false" : "true"}
                  value="false"
                  onPress={() => { setStatus("false") }}
                  label="Tidak Aktif"
                  icon={<AntDesign name="closecircleo" color={status == "false" ? 'white' : colors.dimmed} size={20} />}
                  n={2} />
            </WrapTab>
            <InputSearch onChange={setSearch} />
         </View>
         <View style={[{ flex: 2 }, Styles.mt10]}>
            {
               isLoading ?
                  arrSkeleton.map((item, index) => {
                     return (
                        <SkeletonTwoItem key={index} />
                     )
                  })
                  :
                  data.length > 0 ?
                     <VirtualizedList
                        data={data}
                        getItemCount={() => data.length}
                        getItem={getItem}
                        renderItem={({ item, index }: { item: Props, index: number }) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 onPress={() => {
                                    setIdChoose(item.id)
                                    setActiveChoose(item.isActive)
                                    setTitleChoose(item.name)
                                    setModal(true)
                                 }}
                                 borderType="all"
                                 icon={
                                    <View style={[Styles.iconContent]}>
                                       <Ionicons name="bookmark-outline" size={25} color={'black'} />
                                    </View>
                                 }
                                 title={item.name}
                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                              tintColor={colors.icon}
                           />
                        }
                     />
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada data</Text>
            }
         </View>

         <DrawerBottom animation="slide" isVisible={isModal} setVisible={() => setModal(false)} title={titleChoose}>
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="toggle-switch-off-outline" color={colors.text} size={25} />}
                  title={activeChoose ? "Non Aktifkan" : "Aktifkan"}
                  onPress={() => {
                     setModal(false)
                     setTimeout(() => {
                        setShowDeleteModal(true)
                     }, 600)
                  }}
               />
               <MenuItemRow
                  icon={<MaterialCommunityIcons name="pencil-outline" color={colors.text} size={25} />}
                  title="Edit"
                  onPress={() => {
                     setModal(false)
                     setTimeout(() => {
                        setVisibleEdit(true)
                     }, 600);
                  }}
               />
            </View>
         </DrawerBottom>

         <DrawerBottom animation="none" keyboard height={30} isVisible={isVisibleEdit} setVisible={() => setVisibleEdit(false)} title="Edit Lembaga Desa">
            <View style={{ flex: 1 }}>
               <View>
                  <InputForm
                     type="default"
                     placeholder="Nama Lembaga Desa"
                     required
                     label="Lembaga Desa"
                     value={titleChoose}
                     error={error.title}
                     bg={"transparent"}
                     errorText="Lembaga Desa tidak boleh kosong & minimal 3 karakter"
                     onChange={(val) => { validationForm(val, 'title') }} />
               </View>
               <View>
                  <ButtonForm text="SIMPAN" disabled={Object.values(error).some((v) => v == true) || titleChoose == "" || loadingSubmit} onPress={() => { handleEdit() }} />
               </View>
            </View>
         </DrawerBottom>

         <ModalConfirmation
            visible={showDeleteModal}
            title="Konfirmasi"
            message={activeChoose ? 'Apakah anda yakin ingin menonaktifkan data?' : 'Apakah anda yakin ingin mengaktifkan data?'}
            onConfirm={() => {
               setShowDeleteModal(false)
               handleDelete()
            }}
            onCancel={() => setShowDeleteModal(false)}
            confirmText={activeChoose ? "Nonaktifkan" : "Aktifkan"}
            cancelText="Batal"
         />
      </View >

   )
}