import React from 'react';
import { View, Pressable, Image, StyleSheet } from 'react-native';
import ContextMenu from "../../gusture/contextMenu";
import DownloadSvg from "@/assets/icons/svg/download.svg";
import CancelSvg from "@/assets/icons/svg/cancel.svg";
import { ContentPart } from "@/types/ask";
import { TFunction } from 'i18next';
import { saveMediaToGallery } from "../../ask/utils";

interface MediaGridProps {
  mediaItems: ContentPart[];
  setModalVisible: React.Dispatch<React.SetStateAction<{ visible: boolean, data: ContentPart }>>;
  setCancel: React.Dispatch<React.SetStateAction<boolean>>;
  cancel: boolean;
  t: TFunction;
}

const MediaGrid = ({ mediaItems, setModalVisible, setCancel, cancel, t }: MediaGridProps) => {
  // 只取前6个元素（2行，每行3个）
  const displayItems = mediaItems.slice(0, 6);

  return (
    <View className="flex-row flex-wrap justify-between">
      {displayItems.map((media) => (
        <Pressable
          key={media.id}
          onPress={() => {
            setModalVisible({ visible: true, data: media });
          }}
          className="mb-2 w-[32%] aspect-square"
        >
          <ContextMenu
            items={[
              {
                svg: <DownloadSvg width={20} height={20} />,
                label: t("ask:ask.save"),
                onPress: () => {
                  if (media?.url) {
                    saveMediaToGallery(media?.url, t);
                  }
                },
                textStyle: { color: '#4C320C' }
              },
              {
                svg: <CancelSvg width={20} height={20} color='red' />,
                label: t("ask:ask.cancel"),
                onPress: () => {
                  setCancel(true);
                },
                textStyle: { color: 'red' }
              }
            ]}
            cancel={cancel}
            menuStyle={{
              backgroundColor: 'white',
              borderRadius: 8,
              padding: 8,
              minWidth: 150,
              shadowColor: '#000',
              shadowOffset: { width: 0, height: 2 },
              shadowOpacity: 0.25,
              shadowRadius: 4,
              elevation: 5,
            }}
          >
            <Image
              source={{ uri: media?.url }}
              className="w-full h-full rounded-xl"
              resizeMode="cover"
              loadingIndicatorSource={require('@/assets/images/png/placeholder.png')}
            />
          </ContextMenu>
        </Pressable>
      ))}
    </View>
  );
};



export default MediaGrid;
