import Text from "@/components/Text";
import { regexOnlySpacesOrEnter } from "@/constants/OnlySpaceOrEnter";
import Styles from "@/constants/Styles";
import { useTheme } from "@/providers/ThemeProvider";
import { Feather, Ionicons, MaterialCommunityIcons, MaterialIcons } from "@expo/vector-icons";
import * as DocumentPicker from "expo-document-picker";
import { ActivityIndicator, Platform, Pressable, ScrollView, TextInput, View } from "react-native";
import Toast from "react-native-toast-message";

type Props = {
   mode: 'new' | 'edit' | 'locked'
   lockedReason?: string
   value: string
   onChange: (val: string) => void
   loading: boolean
   onSend: () => void
   onCancelEdit?: () => void
   files?: { uri: string; name: string }[]
   onAddFile?: (files: { uri: string; name: string }[]) => void
   onRemoveFile?: (index: number) => void
   existingFiles?: { id: string; name: string; extension: string }[]
   onRemoveExistingFile?: (id: string) => void
   canSend: boolean
}

export default function DiscussionCommentInput({
   mode, lockedReason, value, onChange, loading, onSend,
   onCancelEdit, files = [], onAddFile, onRemoveFile,
   existingFiles = [], onRemoveExistingFile, canSend
}: Props) {
   const { colors } = useTheme()

   async function pickFiles() {
      const result = await DocumentPicker.getDocumentAsync({ type: ['*/*'], multiple: true })
      if (!result.canceled && onAddFile) {
         let skipped = 0
         const newFiles: { uri: string; name: string }[] = []
         for (const asset of result.assets) {
            if (!asset.uri) continue
            if (files.some(f => f.name === asset.name)) { skipped++; continue }
            newFiles.push({ uri: asset.uri, name: asset.name })
         }
         if (skipped > 0) Toast.show({ type: 'small', text1: 'Beberapa file sudah ditambahkan' })
         if (newFiles.length > 0) onAddFile(newFiles)
      }
   }

   if (mode === 'locked') {
      return (
         <View style={[Styles.pv20, Styles.itemsCenter]}>
            <Text style={[Styles.textInformation, { color: colors.dimmed }]}>{lockedReason}</Text>
         </View>
      )
   }

   const sendDisabled = loading || value.trim() === '' || regexOnlySpacesOrEnter.test(value) || !canSend

   return (
      <View style={{ backgroundColor: colors.background, borderTopWidth: mode === 'edit' ? 1 : 0, borderTopColor: colors.icon + '20' }}>
         {mode === 'edit' && (
            <View style={[Styles.rowSpaceBetween, Styles.pv05, { paddingHorizontal: 12 }]}>
               <View style={Styles.rowItemsCenter}>
                  <Feather name="edit-3" color={colors.text} size={20} style={Styles.mh05} />
                  <Text style={Styles.textMediumSemiBold}>Edit Komentar</Text>
                  {loading && (
                     <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed, marginLeft: 6 }]}>Mengirim...</Text>
                  )}
               </View>
               <Pressable onPress={onCancelEdit} disabled={loading}>
                  <MaterialIcons name="close" color={loading ? colors.dimmed : colors.text} size={20} />
               </Pressable>
            </View>
         )}

         {loading && mode === 'new' && (files.length > 0 || existingFiles.length > 0) && (
            <View style={{ paddingHorizontal: 15, paddingTop: 6 }}>
               <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed }]}>Mengirim...</Text>
            </View>
         )}

         {(existingFiles.length > 0 || files.length > 0) && (
            <ScrollView horizontal style={[Styles.ph15, Styles.pv05]} showsHorizontalScrollIndicator={false}>
               {existingFiles.map((f) => (
                  <Pressable
                     key={f.id}
                     onPress={() => !loading && onRemoveExistingFile?.(f.id)}
                     style={{
                        flexDirection: 'row', alignItems: 'center', gap: 6,
                        paddingHorizontal: 10, paddingVertical: 6,
                        borderRadius: 20, borderWidth: 1,
                        backgroundColor: colors.card, borderColor: colors.icon + '18',
                        marginRight: 8,
                        opacity: loading ? 0.5 : 1
                     }}
                  >
                     <MaterialCommunityIcons name="file-outline" size={14} color={colors.dimmed} />
                     <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed, maxWidth: 100 }]} numberOfLines={1}>
                        {f.name}.{f.extension}
                     </Text>
                     <MaterialIcons name="close" size={14} color='#F03E3E' />
                  </Pressable>
               ))}
               {files.map((f, idx) => (
                  <Pressable
                     key={idx}
                     onPress={() => !loading && onRemoveFile?.(idx)}
                     style={{
                        flexDirection: 'row', alignItems: 'center', gap: 6,
                        paddingHorizontal: 10, paddingVertical: 6,
                        borderRadius: 20, borderWidth: 1,
                        backgroundColor: colors.card, borderColor: colors.icon + '18',
                        marginRight: 8,
                        opacity: loading ? 0.5 : 1
                     }}
                  >
                     <MaterialCommunityIcons name="file-outline" size={14} color={colors.dimmed} />
                     <Text style={[Styles.textSmallSemiBold, { color: colors.dimmed, maxWidth: 100 }]} numberOfLines={1}>
                        {f.name}
                     </Text>
                     <MaterialIcons name="close" size={14} color={colors.dimmed} />
                  </Pressable>
               ))}
            </ScrollView>
         )}

         <View style={{
            flexDirection: 'row', alignItems: 'flex-end',
            paddingHorizontal: 12,
            paddingBottom: Platform.OS === 'ios' ? 10 : 6,
            paddingTop: 6,
            gap: 8
         }}>
            {mode === 'new' && (
               <Pressable
                  onPress={pickFiles}
                  disabled={loading}
                  style={{ marginBottom: 6 }}
               >
                  <MaterialIcons
                     name="add"
                     size={28}
                     color={loading ? colors.dimmed + '60' : files.length > 0 ? colors.tabActive : colors.dimmed}
                  />
               </Pressable>
            )}

            <View style={{
               flex: 1,
               backgroundColor: colors.input,
               borderRadius: 30, borderWidth: 1, borderColor: colors.icon + '20',
               paddingHorizontal: 14,
               paddingVertical: 10,
               opacity: loading ? 0.6 : 1
            }}>
               <TextInput
                  style={{
                     color: colors.text,
                     maxHeight: 100,
                     paddingVertical: Platform.OS === 'android' ? 4 : 0,
                     textAlignVertical: 'bottom',
                  }}
                  placeholder="Kirim Komentar"
                  placeholderTextColor={colors.dimmed}
                  value={value}
                  onChangeText={onChange}
                  multiline
                  editable={!loading}
               />
            </View>

            <Pressable
               onPress={() => !sendDisabled && onSend()}
               style={{
                  width: 40, height: 40, borderRadius: 20,
                  backgroundColor: sendDisabled ? colors.dimmed + '40' : colors.tint,
                  justifyContent: 'center', alignItems: 'center',
               }}
            >
               {loading
                  ? <ActivityIndicator size={18} color={sendDisabled ? colors.dimmed : colors.background} />
                  : <Ionicons name="send" size={18} color={sendDisabled ? colors.dimmed : colors.background} />
               }
            </Pressable>
         </View>
      </View>
   )
}
