import { ConstEnv } from "@/constants/ConstEnv";
import { isImageFile } from "@/constants/FileExtensions";
import Styles from "@/constants/Styles";
import { apiGetDivisionOneFeature } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import * as FileSystem from 'expo-file-system';
import { startActivityAsync } from 'expo-intent-launcher';
import { useLocalSearchParams } from "expo-router";
import * as Sharing from 'expo-sharing';
import { useEffect, useState } from "react";
import { Platform, Pressable, ScrollView, View } from "react-native";
import ImageViewing from "react-native-image-viewing";
import * as mime from 'react-native-mime-types';
import Toast from "react-native-toast-message";
import Skeleton from "../skeleton";
import { useTheme } from "@/providers/ThemeProvider";
import Text from "../Text";

type Props = {
   id: string
   name: string
   extension: string
   path: string
   share: boolean
   idStorage: string
}

function getFileIconColor(ext: string): string {
   const e = ext.toLowerCase()
   if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(e)) return '#339AF0'
   if (e === 'pdf') return '#F03E3E'
   if (['doc', 'docx'].includes(e)) return '#1C7ED6'
   if (['xls', 'xlsx', 'csv'].includes(e)) return '#2F9E44'
   if (['ppt', 'pptx'].includes(e)) return '#F97316'
   if (['zip', 'rar', '7z'].includes(e)) return '#E8590C'
   return '#868E96'
}

function getFileIcon(ext: string): string {
   const e = ext.toLowerCase()
   if (isImageFile(e)) return 'image-outline'
   if (e === 'pdf') return 'file-pdf-box'
   if (['doc', 'docx'].includes(e)) return 'file-word-outline'
   if (['xls', 'xlsx', 'csv'].includes(e)) return 'file-excel-outline'
   if (['ppt', 'pptx'].includes(e)) return 'file-powerpoint-outline'
   if (['zip', 'rar', '7z'].includes(e)) return 'folder-zip-outline'
   return 'file-document-outline'
}

export default function FileDivisionDetail({ refreshing }: { refreshing: boolean }) {
   const { colors } = useTheme();
   const [data, setData] = useState<Props[]>([])
   const { token, decryptToken } = useAuthSession()
   const { id } = useLocalSearchParams<{ id: string }>()
   const [loading, setLoading] = useState(true)
   const [loadingOpen, setLoadingOpen] = useState(false)
   const [previewFile, setPreviewFile] = useState<Props | null>(null)

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDivisionOneFeature({ user: hasil, id, cat: 'new-file' })
         setData(response.data)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   useEffect(() => {
      if (refreshing) handleLoad(false)
   }, [refreshing])

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

   async function openExternal(item: Props) {
      try {
         setLoadingOpen(true)
         const remoteUrl = `${ConstEnv.url_storage}/files/${item.idStorage}`
         const fileName = `${item.name}.${item.extension}`
         const localPath = `${FileSystem.documentDirectory}/${fileName}`
         const dl = await FileSystem.downloadAsync(remoteUrl, localPath)
         if (dl.status !== 200) throw new Error('Download failed')
         const contentURL = await FileSystem.getContentUriAsync(dl.uri)
         const mimeType = mime.lookup(fileName) as string
         if (Platform.OS === 'android') {
            await startActivityAsync('android.intent.action.VIEW', { data: contentURL, flags: 1, type: mimeType })
         } else {
            await Sharing.shareAsync(localPath)
         }
      } catch {
         Toast.show({ type: 'error', text1: 'Gagal membuka file' })
      } finally {
         setLoadingOpen(false)
      }
   }

   function handleFilePress(item: Props) {
      if (isImageFile(item.extension.toLowerCase())) {
         setPreviewFile(item)
      } else {
         openExternal(item)
      }
   }

   return (
      <View style={[Styles.mb15]}>
         <Text style={[Styles.textDefaultSemiBold, Styles.mv10]}>Dokumen Terkini</Text>
         {loading ? (
            <View style={{ flexDirection: 'row', gap: 8 }}>
               <Skeleton width={160} widthType="pixel" height={60} borderRadius={8} />
               <Skeleton width={160} widthType="pixel" height={60} borderRadius={8} />
               <Skeleton width={160} widthType="pixel" height={60} borderRadius={8} />
            </View>
         ) : data.length > 0 ? (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 8 }}>
               {data.map((item, index) => {
                  const iconColor = getFileIconColor(item.extension)
                  const iconName = getFileIcon(item.extension)
                  return (
                     <Pressable
                        key={index}
                        onPress={() => handleFilePress(item)}
                        style={({ pressed }) => ({
                           flexDirection: 'row', alignItems: 'center', gap: 10,
                           paddingHorizontal: 12, paddingVertical: 10,
                           borderRadius: 8, borderWidth: 1,
                           backgroundColor: pressed ? colors.icon + '08' : colors.card,
                           borderColor: colors.icon + '20',
                           width: 160,
                        })}
                     >
                        <View style={{
                           width: 40, height: 40, borderRadius: 8,
                           backgroundColor: iconColor + '20',
                           alignItems: 'center', justifyContent: 'center',
                           flexShrink: 0,
                        }}>
                           <MaterialCommunityIcons name={iconName as any} size={22} color={iconColor} />
                        </View>
                        <View style={{ flexShrink: 1 }}>
                           <Text style={[Styles.textSmallSemiBold, { color: colors.text }]} numberOfLines={1}>
                              {item.name}
                           </Text>
                           <Text style={[Styles.textInformation, { color: colors.dimmed, marginTop: 2 }]}>
                              {item.extension.toUpperCase()}
                           </Text>
                        </View>
                     </Pressable>
                  )
               })}
            </ScrollView>
         ) : (
            <View style={{ alignItems: 'center', paddingVertical: 16, gap: 6, opacity: 0.5 }}>
               <MaterialCommunityIcons name="file-document-outline" size={28} color={colors.dimmed} />
               <Text style={[Styles.textDefault, { color: colors.dimmed }]}>Belum ada dokumen</Text>
            </View>
         )}

         <ImageViewing
            images={[{ uri: `${ConstEnv.url_storage}/files/${previewFile?.idStorage}` }]}
            imageIndex={0}
            visible={previewFile !== null}
            onRequestClose={() => setPreviewFile(null)}
            doubleTapToZoomEnabled
            HeaderComponent={() => (
               <View style={Styles.headerModalViewImg}>
                  <Pressable onPress={() => setPreviewFile(null)}>
                     <Text style={{ color: 'white', fontSize: 26 }}>✕</Text>
                  </Pressable>
                  <Pressable onPress={() => previewFile && openExternal(previewFile)} disabled={loadingOpen}>
                     <Text style={{ color: loadingOpen ? 'gray' : 'white', fontSize: 26 }}>⋯</Text>
                  </Pressable>
               </View>
            )}
            FooterComponent={() => (
               <View style={{ paddingBottom: 20, paddingHorizontal: 16, alignItems: 'center' }}>
                  <Text style={{ color: 'white', fontSize: 16 }}>{previewFile?.name}.{previewFile?.extension}</Text>
               </View>
            )}
         />
      </View>
   )
}
