import { useContext, useEffect, useRef, useState } from "react";
import { AppContext, AppStyles, ModalContainer } from "../../utils";
import {
  Modal,
  Pressable,
  SafeAreaView,
  Text,
  TouchableWithoutFeedback,
  View,
  FlatList,
} from "react-native";
import MyIcon from "../Icon";
import MyTextInput from "../TextInput";
import { MyIconButton } from "../Button";
import { Divider } from "../Divider";
import MyPressable from "../Pressable";
import Animated, {
  Easing,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
  withTiming,
} from "react-native-reanimated";
import { StatusBar } from "expo-status-bar";

//const modalContentStyle = { margin: 10, paddingTop: 10 };

/*
transparent: set this to prevent modal reopening on iOS
https://github.com/facebook/react-native/issues/34018
*/
/*
export default function MyModal({
  children,
  isOpen,
  closeModal,
  header,
  content,
  disableAnimationForIos,
  scrollView,
  disableDefaultContentStyle,
}) {
  const appContext = useContext(AppContext);

  const getContent = () => {
    if (scrollView) {
      return (
        <ScrollView>
          <View style={[!disableDefaultContentStyle && modalContentStyle]}>
            {content}
          </View>
        </ScrollView>
      );
    }

    return (
      <View style={[!disableDefaultContentStyle && modalContentStyle]}>
        {content}
      </View>
    );
  };

  return (
    <View>
      <Modal
        visible={isOpen}
        animationType={
          disableAnimationForIos && IsPlatformIos() ? "none" : "slide"
        }
        onRequestClose={() => closeModal()}
        transparent
      >
        {children}

        <View
          style={[
            {
              flex: 1,
              backgroundColor: appContext.appTheme.backgroundColor,
              paddingTop: IsPlatformIos() ? 30 : 15,
            },
            ,
          ]}
        >
          {header}

          {getContent()}
        </View>
      </Modal>
    </View>
  );
}

export function MyDefaultModalHeader({ title, closeModal }) {
  const appContext = useContext(AppContext);

  return (
    <View
      style={{
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
      }}
    >
      <TouchableOpacity onPress={() => closeModal()}>
        <MyIcon name="chevron-left" size={24} style={{ marginLeft: 20 }} />
      </TouchableOpacity>

      <Text
        style={[
          AppStyles.typography20,
          { fontWeight: "bold", color: appContext.appTheme.text },
        ]}
      >
        {title}
      </Text>

      <View style={{ marginRight: 40 }} />
    </View>
  );
} */

export function MyDotsModal({ modalData }) {
  const [isDotsModalOpen, setIsDotsModalOpen] = useState(false);

  return (
    <>
      <MyIconButton
        iconName="dots-vertical"
        iconSize={24}
        style={AppStyles.headerNavigationIcons}
        onPress={() => setIsDotsModalOpen(true)}
      />

      <DotsModal
        isOpen={isDotsModalOpen}
        closeModal={() => setIsDotsModalOpen(false)}
        data={modalData}
      />
    </>
  );
}

function DotsModal({ isOpen, closeModal, data }) {
  const appContext = useContext(AppContext);

  const listItemStyle = (isFirst, isLast) => {
    return {
      borderTopLeftRadius: isFirst ? 10 : 0,
      borderTopRightRadius: isFirst ? 10 : 0,
      borderBottomLeftRadius: isLast ? 10 : 0,
      borderBottomRightRadius: isLast ? 10 : 0,
    };
  };

  const handleBackdropPress = (e) => {
    const x = e.nativeEvent.locationX;
    const y = e.nativeEvent.locationY;

    const topLeftX = 0;
    const topLeftY = 0;
    const bottomRightX = 200; // width
    const bottomRightY = 52; // height of item

    if (
      x < topLeftX ||
      x > bottomRightX ||
      x < bottomRightX ||
      y < topLeftY ||
      y > bottomRightY
    ) {
      closeModal();
    }
  };

  return (
    <Modal
      visible={isOpen}
      transparent
      style={{ flex: 1 }}
      onRequestClose={() => closeModal()}
    >
      <SafeAreaView style={{ flex: 1 }}>
        <Pressable onPress={handleBackdropPress} style={{ flex: 1 }}>
          <View
            style={[
              {
                marginTop: 10,
                backgroundColor: appContext.appTheme.card.backgroundColor,
                width: 200,
                borderRadius: 10,
                alignSelf: "flex-end",
              },
              AppStyles.Shadow,
            ]}
          >
            <FlatList
              scrollEnabled={false}
              data={data}
              renderItem={({ item, index }) => (
                <MyPressable
                  key={index}
                  style={listItemStyle(index === 0, index === data.length - 1)}
                  backgroundColor={appContext.appTheme.card.backgroundColor}
                  onPress={() => {
                    closeModal();
                    item.onPress();
                  }}
                  disabled={item.disabled}
                >
                  <View
                    style={[
                      {
                        flexDirection: "row",
                        alignItems: "center",
                        gap: 10,
                        padding: 16,
                      },
                      item.disabled && AppStyles.disabled,
                    ]}
                  >
                    <MyIcon name={item.icon} size={24} />
                    <Text style={{ color: appContext.appTheme.text }}>
                      {item.label}
                    </Text>
                  </View>
                </MyPressable>
              )}
            />
          </View>
        </Pressable>
      </SafeAreaView>
    </Modal>
  );
}

export function MyPickerModalListItem({
  onPress,
  itemName,
  itemSelected,
  disabled,
  pressableBackgroundColor,
  leftIconName,
  rightIconName,
}) {
  const appContext = useContext(AppContext);

  const rIconName =
    rightIconName === undefined
      ? "checkbox-blank-circle-outline"
      : rightIconName;

  const TextComponent = () => {
    return (
      <Text
        style={[
          AppStyles.typography16,
          { color: appContext.appTheme.text },
          disabled && AppStyles.disabled,
        ]}
      >
        {itemName}
      </Text>
    );
  };

  return (
    <MyPressable
      backgroundColor={pressableBackgroundColor}
      onPress={onPress}
      disabled={disabled}
    >
      <View
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
          padding: 12,
        }}
      >
        {leftIconName !== undefined ? (
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              gap: 10,
            }}
          >
            <MyIcon
              name={leftIconName}
              size={24}
              color={appContext.appTheme.icon}
            />
            <TextComponent />
          </View>
        ) : (
          <TextComponent />
        )}

        {itemSelected ? (
          <MyIcon
            name="checkbox-marked-circle"
            size={24}
            color={appContext.appTheme.colors.primary}
          />
        ) : (
          <MyIcon
            name={rIconName}
            size={24}
            color={appContext.appTheme.colors.gray}
            style={disabled && AppStyles.disabled}
          />
        )}
      </View>
      <Divider withoutMarginVertical />
    </MyPressable>
  );
}

export function MyTextInputModalContent({
  navigation,
  defaultValue,
  onCheckIconPress,
  textInputTitle,
  textInputDescription,
  textMaxLength,
  textOnSubmitEditing,
}) {
  const [newValue, setNewValue] = useState(defaultValue);

  useEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <MyIconButton
          usePrimaryColor
          iconName="check"
          iconSize={24}
          style={AppStyles.headerNavigationIcons}
          onPress={() => {
            navigation.goBack();
            onCheckIconPress(newValue);
          }}
          disabled={newValue.length === 0}
        />
      ),
    });
  }, [navigation, newValue]);

  return (
    <ModalContainer>
      <MyTextInput
        textTitle={textInputTitle}
        textDescription={textInputDescription}
        value={newValue}
        onChangeText={(v) => setNewValue(v)}
        textMaxLength={textMaxLength}
        onSubmitEditing={(e) => {
          navigation.goBack();
          textOnSubmitEditing(e);
        }}
      />
    </ModalContainer>
  );
}

export function MyBottomSheetModal({
  children,
  isOpen,
  closeModal,
  modalHeight,
  headerTitle,
}) {
  const appContext = useContext(AppContext);

  const translateY = useSharedValue(0);
  const opacity = useSharedValue(0);

  translateY.value = withTiming(isOpen ? 0 : modalHeight, {
    duration: 250,
    easing: Easing.ease,
  });

  opacity.value = withTiming(isOpen ? 1 : 0, {
    duration: 250,
    easing: Easing.ease,
  });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateY: translateY.value }],
    opacity: opacity.value,
  }));

  const handleCloseModal = () => {
    translateY.value = withTiming(modalHeight, {
      duration: 100,
      easing: Easing.ease,
    });

    opacity.value = withTiming(0, { duration: 100, easing: Easing.ease });

    setTimeout(() => closeModal(), 100);
  };

  return (
    <Modal
      statusBarTranslucent
      visible={isOpen}
      transparent
      style={{ flex: 1 }}
      onRequestClose={() => handleCloseModal()}
    >
      <TouchableWithoutFeedback onPress={() => handleCloseModal()}>
        <View
          style={{
            flex: 1,
            backgroundColor:
              appContext.appTheme.modal.transparentBackgroundColor,
          }}
        />
      </TouchableWithoutFeedback>

      <View
        style={{
          backgroundColor: appContext.appTheme.modal.transparentBackgroundColor,
        }}
      >
        <Animated.View
          style={[
            {
              backgroundColor: appContext.appTheme.card.backgroundColor,
              borderTopLeftRadius: 20,
              borderTopRightRadius: 20,
              height: modalHeight,
              shadowRadius: 8,
              shadowOffset: {
                width: 0,
                height: -10,
              },
              shadowColor: "#000000",
              elevation: 6,
              paddingTop: 20,
            },
            animatedStyle,
          ]}
        >
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-between",
              paddingLeft: 20,
              paddingRight: 18,
              paddingBottom: 2,
            }}
          >
            <Text
              style={[
                { color: appContext.appTheme.text, fontWeight: "bold" },
                AppStyles.typography16,
              ]}
            >
              {headerTitle}
            </Text>

            <MyIconButton
              style={{ padding: 2 }}
              iconSize={24}
              iconColor={appContext.appTheme.icon}
              iconName="close"
              onPress={() => handleCloseModal()}
            />
          </View>

          {children}
        </Animated.View>
      </View>
    </Modal>
  );
}

/*
export function MyPickerModal({ isOpen, setIsOpen, items, searchFilter }) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();
  const [providedItems, setProvidedItems] = useState([]);
  const [searchFilterInput, setSearchFilterInput] = useState("");

  useEffect(() => setProvidedItems(items), [items]);

  const closeModal = () => {
    setIsOpen(false);
    setProvidedItems(items);
    setSearchFilterInput("");
  };

  return (
    <Modal
      visible={isOpen}
      animationType="slide"
      onRequestClose={() => closeModal()}
    >
      <KeyboardAvoidingView
        behavior={IsPlatformIos() ? "padding" : "height"}
        style={[
          {
            flex: 1,
            backgroundColor: appContext.appTheme.backgroundColor,
          },
        ]}
      >
        <View style={{ flexDirection: "row", alignItems: "center" }}>
          <TouchableOpacity onPress={() => closeModal()}>
            <MyIcon
              name={searchFilter ? "chevron-left" : "window-close"}
              size={24}
              style={{ marginLeft: 20, marginTop: 20, marginBottom: 20 }}
              color={appContext.appTheme.icon}
            />
          </TouchableOpacity>

          {searchFilter && (
            <View
              style={{
                flex: 1,
                flexDirection: "row",
                alignItems: "center",
                justifyContent: "center",
                borderBottomWidth: 1,
                borderColor: appContext.appTheme.textInputBottomColor,
                marginLeft: 10,
                marginRight: 10,
              }}
            >
              <MyIcon
                style={{ marginLeft: 10 }}
                name="magnify"
                size={22}
                color={appContext.appTheme.icon}
              />
              <TextInput
                style={{
                  flex: 1,
                  height: 40,
                  marginLeft: 10,
                  marginRight: 10,
                }}
                placeholder={t("common.textInputPlaceholderSearch")}
                value={searchFilterInput}
                onChangeText={(text) => {
                  setSearchFilterInput(text);

                  setProvidedItems(() =>
                    items.filter((provItem) => {
                      return provItem.label
                        .toLowerCase()
                        .startsWith(text.toLowerCase());
                    })
                  );
                }}
              />
              {searchFilterInput !== "" && (
                <TouchableOpacity
                  onPress={() => {
                    setSearchFilterInput("");
                    setProvidedItems(items);
                  }}
                >
                  <MyIcon
                    style={{ marginRight: 10 }}
                    name="close"
                    size={20}
                    color={appContext.appTheme.icon}
                  />
                </TouchableOpacity>
              )}
            </View>
          )}
        </View>

        {providedItems.length === 0 && (
          <View
            style={{
              flex: 1,
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <MyIcon
              name="magnify-remove-outline"
              color={appContext.appTheme.icon}
              size={64}
            />
            <Text style={[AppStyles.typography20, { marginTop: 20 }]}>
              {t("common.pickerSearchFilterNoResults")}
            </Text>
          </View>
        )}

        {providedItems.map((item, i) => {
          return item.selected ? (
            <View key={i}>
              <TouchableOpacity onPress={() => closeModal()}>
                <View
                  style={{
                    flexDirection: "row",
                    justifyContent: "space-between",
                    marginLeft: 20,
                    marginRight: 20,
                  }}
                >
                  <Text
                    style={[
                      AppStyles.typography16,
                      { color: appContext.appTheme.text },
                    ]}
                  >
                    {item.label}
                  </Text>
                  <MyIcon
                    name="check"
                    size={24}
                    color={appContext.appTheme.colors.primary}
                  />
                </View>
              </TouchableOpacity>
              <Divider />
            </View>
          ) : (
            <View key={i}>
              <TouchableOpacity
                onPress={() => {
                  closeModal();
                  item.onPress();
                }}
              >
                <Text
                  style={[
                    AppStyles.typography16,
                    { marginLeft: 20, color: appContext.appTheme.text },
                  ]}
                >
                  {item.label}
                </Text>
              </TouchableOpacity>
              <Divider />
            </View>
          );
        })}
      </KeyboardAvoidingView>
    </Modal>
  );
}*/
/*
export function MyTextInputModal({
  isOpen,
  setIsOpen,
  onTextInputSave,
  modalTitle,
  inputTitle,
  inputDescription,
}) {
  const appContext = useContext(AppContext);

  const closeModal = () => setIsOpen(false);

  return (
    <Modal
      visible={isOpen}
      animationType="slide"
      onRequestClose={() => closeModal()}
    >
      <View
        style={[
          {
            flex: 1,
            backgroundColor: appContext.appTheme.backgroundColor,
          },
        ]}
      >
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            marginTop: 20,
          }}
        >
          <TouchableOpacity onPress={() => closeModal()}>
            <MyIcon
              name="chevron-left"
              size={24}
              style={{ marginLeft: 20 }}
              color={appContext.appTheme.icon}
            />
          </TouchableOpacity>
          <Text style={AppStyles.typography20}>{modalTitle}</Text>
          <TouchableOpacity
            onPress={() => {
              closeModal();
              onTextInputSave();
            }}
          >
            <MyIcon
              name="check"
              size={24}
              style={{ marginRight: 20 }}
              color={appContext.appTheme.colors.primary}
            />
          </TouchableOpacity>
        </View>

        <View
          style={{
            flex: 1,
            padding: 20,
          }}
        >
          <Text style={{ color: "gray" }}>{inputTitle}</Text>
          <TextInput
            style={{
              height: 40,
              borderBottomWidth: 1,
              borderColor: appContext.appTheme.textInputBottomColor,
            }}
            value="Turtle"
          />
          <Text
            style={[AppStyles.typography14, { color: "gray", marginTop: 6 }]}
          >
            {inputDescription}
          </Text>
        </View>
      </View>
    </Modal>
  );
}
*/
