import React, { useCallback, useState } from 'react';
import { StyleSheet, TouchableOpacity, View, Text, Button } from 'react-native';
import ActionSheet, { Route, SheetManager, useSheetRouter } from 'react-native-actions-sheet';
import { getFontSize } from 'src/utils';
import { Colors } from 'src/theme';
import { WarningProps } from '../types';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { usePostReportConversationMutation } from '@api/chat';
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'react-native-document-picker';

import MegaphoneIcon from 'assets/icons/messages/megaphone.svg';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import RouteB from './RouteB';

const AttachmentsModal = () => {
  const insets = useSafeAreaInsets();
  const [chatData, setChatData] = useState<any>(null);
  const [shouldOpenWarningModal, setShouldOpenWarningModal] = useState<WarningProps | null>(null);
  const { mutateAsync: reportUser } = usePostReportConversationMutation();

  const router = useSheetRouter('sheet-router');

  const [currentLocation, setCurrentLocation] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);
  const [selectedLocation, setSelectedLocation] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const handleSheetOpen = (payload: any) => {
    setChatData(payload);
  };

  const handleReport = async () => {
    if (!chatData) return;

    setShouldOpenWarningModal({
      title: `Report ${chatData.name}`,
      buttonTitle: 'Report',
      message: `Are you sure you want to report ${chatData.name}?\nIf you proceed, the chat history with ${chatData.name} will become visible to NomadMania admins for investigation.`,
      action: async () => {
        await reportUser({
          token: chatData.token,
          reported_user_id: chatData.uid
        });
      }
    });

    setTimeout(() => {
      SheetManager.hide('chat-attachments');
      setShouldOpenWarningModal(null);
    }, 300);
  };

  const handleOpenGallery = useCallback(async () => {
    if (!chatData) return;
    try {
      const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (!perm.granted) {
        console.warn('Permission for gallery not granted');
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsMultipleSelection: true,
        quality: 1,
        selectionLimit: 4
      });

      if (!result.canceled && result.assets) {
        const files = result.assets.map((asset) => ({
          uri: asset.uri,
          type: asset.type === 'video' ? 'video' : 'image'
        }));
        chatData.onSendMedia(files);
      }
      SheetManager.hide('chat-attachments');
    } catch (err) {
      console.warn('Gallery error: ', err);
    }
  }, [chatData?.onSendMedia, chatData?.closeOptions]);

  const handleOpenCamera = useCallback(async () => {
    if (!chatData) return;
    try {
      const perm = await ImagePicker.requestCameraPermissionsAsync();
      if (!perm.granted) {
        console.warn('Permission for camera not granted');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        quality: 1
      });

      if (!result.canceled && result.assets) {
        const files = result.assets.map((asset) => ({
          uri: asset.uri,
          type: asset.type === 'video' ? 'video' : 'image'
        }));
        chatData.onSendMedia(files);
      }
      SheetManager.hide('chat-attachments');
    } catch (err) {
      console.warn('Camera error: ', err);
    }
  }, [chatData?.onSendMedia, chatData?.closeOptions]);

  const handleShareLiveLocation = useCallback(() => {
    if (!chatData) return;
    chatData.onShareLiveLocation();
    SheetManager.hide('chat-attachments');
  }, [chatData?.onShareLiveLocation, chatData?.closeOptions]);

  const handleSendFile = useCallback(async () => {
    if (!chatData) return;

    try {
      const res = await DocumentPicker.pick({
        type: [DocumentPicker.types.allFiles],
        allowMultiSelection: false
      });

      const file = {
        uri: res[0].uri,
        name: res[0].name,
        type: res[0].type
      };

      if (chatData.onSendFile) {
        chatData.onSendFile([file]);
      }
    } catch (err) {
      if (DocumentPicker.isCancel(err)) {
        console.log('User canceled document picker');
      } else {
        console.warn('DocumentPicker error:', err);
      }
    }

    SheetManager.hide('chat-attachments');
  }, [chatData?.onSendFile, chatData?.closeOptions]);

  const RouteA = () => {
    const router = useSheetRouter('sheet-router');
    return (
      <View
        style={[
          styles.container,
          { paddingBottom: 8 + insets.bottom, backgroundColor: Colors.FILL_LIGHT }
        ]}
      >
        <View style={styles.optionRow}>
          <TouchableOpacity style={styles.optionItem} onPress={handleOpenGallery}>
            <MaterialCommunityIcons name="image" size={36} color={Colors.ORANGE} />
            <Text style={styles.optionLabel}>Gallery</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.optionItem} onPress={handleOpenCamera}>
            <MaterialCommunityIcons name="camera" size={36} color={Colors.ORANGE} />
            <Text style={styles.optionLabel}>Camera</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.optionItem}
            onPress={() => {
              router?.navigate('route-b');
            }}
          >
            <MaterialCommunityIcons name="map-marker" size={36} color={Colors.ORANGE} />
            <Text style={styles.optionLabel}>Location</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.optionItem} onPress={handleShareLiveLocation}>
            <MaterialCommunityIcons name="navigation" size={36} color={Colors.ORANGE} />
            <Text style={styles.optionLabel}>Live</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.optionItem} onPress={handleSendFile}>
            <MaterialCommunityIcons name="file" size={36} color={Colors.ORANGE} />
            <Text style={styles.optionLabel}>File</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.optionItem} onPress={handleReport}>
            <MegaphoneIcon fill={Colors.RED} width={36} height={36} />
            <Text style={styles.optionLabel}>Report</Text>
          </TouchableOpacity>
          <View style={styles.optionItem}></View>
        </View>
      </View>
    );
  };

  const routes: Route[] = [
    {
      name: 'route-a',
      component: RouteA
    },
    {
      name: 'route-b',
      component: RouteB,
      params: { onSendLocation: chatData?.onSendLocation, insetsBottom: insets.bottom }
    }
  ];

  return (
    <ActionSheet
      id="chat-attachments"
      gestureEnabled={true}
      containerStyle={{
        backgroundColor: Colors.FILL_LIGHT
      }}
      enableRouterBackNavigation={true}
      routes={routes}
      initialRoute="route-a"
      defaultOverlayOpacity={0}
      indicatorStyle={{ backgroundColor: Colors.WHITE }}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      onClose={() => {
        if (shouldOpenWarningModal) {
          chatData?.setModalInfo({
            visible: true,
            type: 'delete',
            title: shouldOpenWarningModal.title,
            buttonTitle: shouldOpenWarningModal.buttonTitle,
            message: shouldOpenWarningModal.message,
            action: shouldOpenWarningModal.action
          });
        }
      }}
    />
  );
};

const styles = StyleSheet.create({
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  optionText: {
    fontSize: getFontSize(12),
    fontWeight: '600',
    color: Colors.DARK_BLUE
  },
  dangerOption: {
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBlockColor: Colors.WHITE
  },
  dangerText: {
    color: Colors.RED
  },
  container: {
    backgroundColor: Colors.WHITE
  },
  optionRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: '5%',
    marginVertical: 20,
    flexWrap: 'wrap'
  },
  optionItem: {
    width: '30%',
    paddingVertical: 8,
    marginBottom: 12,
    alignItems: 'center'
  },
  optionLabel: {
    marginTop: 6,
    fontSize: 12,
    color: Colors.DARK_BLUE,
    fontWeight: '700'
  }
});

export default AttachmentsModal;
