import {
  Pressable,
  TextInput,
  InputAccessoryView,
  Text,
  View,
  Image,
  Keyboard,
  Platform,
} from "react-native";
import { useState } from "react";
import CountryPicker, { DARK_THEME } from "react-native-country-picker-modal";
import usePlaceApi from "react-native-minuit/src/hooks/usePlacesApi";

import { art, icons } from "../assets";
import { Fonts, Palette, Style, gutters } from "../styles";
import { FONT_FAMILY, fontTypeList } from "../styles/Fonts";

import { isWeb } from "../hooks/useLayoutType";
import { GOOGLE_API_KEY } from "../data/keys";
import { BlurView } from "expo-blur";

const Input = ({
  inputRef = null,
  label = "",
  placeholder = "",

  containerStyle = {},
  textInputStyle = {},

  value,
  setValue,

  textInputProps = {},

  type = "default", // "default" | "password" | "textarea" | "coinAmount" | "countryPicker" | "autoCompleteAddress"
  theme = "default", // "default" | "radioactiv" | "dashed"

  borderType = "none", // "solid" | "dashed" | "none"

  layout = "default", // "default" | "line"

  isNumeric = false,
  isBlur = false,
}) => {
  const [isFocused, setIsFocused] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showCountryPicker, setShowCountryPicker] = useState(false);

  const isDefaultLayout = layout === "default";

  const mainColor =
    theme === "radioactiv" ? Palette.radioactivGreen : Palette.primary;

  const isRoundedRectangle =
    ["textarea", "coinAmount"].includes(type) || layout === "default";

  const inputAccessoryViewID = "uniqueID";

  const { places } = usePlaceApi({
    query: type === "autoCompleteAddress" ? value : "",
    apiKey: GOOGLE_API_KEY, // Your Google API Key
    queryFields: "formatted_address,geometry,name,address_components",
    queryCountries: ["fr"],
    language: "fr-FR",
    minChars: 2,
  });

  const ContainerView = isBlur ? BlurView : View;

  return (
    <>
      <View
        style={{
          width: "100%",
          ...containerStyle,
          gap: 4,
        }}
      >
        {label?.length > 0 && (
          <Text
            style={{
              fontSize: 14,
              color: Palette.white,
              fontFamily: FONT_FAMILY.HelveticaNeueRegular,
            }}
          >
            {label}
          </Text>
        )}

        <ContainerView
          tint="dark"
          experimentalBlurMethod={
            Platform.OS !== "ios" ? "dimezisBlurView" : "none"
          }
          style={{
            ...Style.containerRow,
            ...(isRoundedRectangle
              ? {
                  ...Style.containerItem,
                  ...(isDefaultLayout
                    ? {
                        paddingVertical: 10,
                        backgroundColor:
                          type === "coinAmount"
                            ? Palette.transparentRadioactivGreen
                            : Palette.glass,
                        height: type === "textarea" ? 150 : 50,
                        overflow: "hidden",
                        borderRadius: 12,
                      }
                    : {}),
                }
              : {
                  ...Style.containerCenter,
                  borderBottomColor: mainColor,
                  borderBottomWidth: 1,
                }),
            ...(borderType === "dashed"
              ? {
                  borderStyle: "dashed",
                  borderColor: isFocused
                    ? Palette.primary
                    : Palette.transparentPrimary,
                  borderWidth: 1,
                }
              : {}),
            width: "100%",
          }}
        >
          {type === "search" ? (
            <Image
              source={icons.search}
              style={[Style.iconDefault, { marginRight: 10 }]}
              resizeMode="contain"
            />
          ) : null}

          {type === "countryPicker" ? (
            <CountryPicker
              countryCode={value}
              onSelect={(country) => {
                console.log(country);
                setValue(country.cca2);
              }}
              visible={showCountryPicker}
              theme={{
                ...DARK_THEME,
                primaryColor: Palette.primary,
                backgroundColor: Palette.darkPurple,
                ...fontTypeList.default,
              }}
              closeButtonImage={icons.arrowRight}
              closeButtonStyle={[Style.mirrorHorizontal]}
              withEmoji={true}
              withFilter={true}
              withAlphaFilter={false}
              withCountryNameButton={true}
              containerButtonStyle={{ padding: 0, margin: 0 }}
              translation="fra"
              placeholder={"Sélectionnez un pays"}
              countryName={value}
              preferredCountries={["FR", "BE", "CH", "LU", "CA", "US", "GB"]}
              filterProps={{
                placeholder: "Rechercher un pays",
                style: {
                  ...Fonts({}),
                },
              }}
            />
          ) : (
            <TextInput
              ref={inputRef}
              placeholder={placeholder}
              placeholderTextColor={Palette.gray}
              value={value}
              onChangeText={setValue}
              multiline={type === "textarea"}
              editable={type !== "countryPicker"}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
              style={{
                width: "100%",
                ...(isRoundedRectangle
                  ? {
                      height: "100%",
                      flex: 1,
                      textAlignVertical: type === "textarea" ? "top" : "center",
                    }
                  : { textAlign: "center" }),
                fontSize: 14,
                color: Palette.white,
                fontFamily: FONT_FAMILY.InterRegular,
                ...(isWeb
                  ? {
                      lineHeight: "auto",
                    }
                  : {}),
                ...textInputStyle,
              }}
              {...(type === "password"
                ? {
                    secureTextEntry: !showPassword,
                    autoCapitalize: "none",
                    autoCompleteType: "password",
                    textContentType: "password",
                  }
                : {})}
              {...(type === "email"
                ? {
                    keyboardType: "email-address",
                    autoCapitalize: "none",
                    autoCompleteType: "email",
                    textContentType: "emailAddress",
                  }
                : {})}
              keyboardType={isNumeric ? "numeric" : "default"}
              keyboardAppearance="dark"
              inputAccessoryViewID={inputAccessoryViewID}
              {...textInputProps}
            />
          )}

          {type === "password" ? (
            <Pressable onPress={() => setShowPassword(!showPassword)}>
              <Image
                source={icons.eye}
                style={[Style.iconDefault]}
                resizeMode="contain"
              />
            </Pressable>
          ) : type === "coinAmount" ? (
            <Image
              source={art.coin}
              style={[Style.iconDefault]}
              resizeMode="contain"
            />
          ) : null}
        </ContainerView>

        {type === "autoCompleteAddress" &&
          places?.[0]?.description &&
          places?.[0]?.description !== value &&
          places.map((place, index) => (
            <Pressable
              key={index}
              onPress={() => {
                setValue(place?.description);
              }}
              style={{
                ...Style.containerSpaceBetween,
                marginBottom: index !== places.length - 1 ? gutters / 2 : 0,
              }}
            >
              <Text
                style={{
                  ...Fonts({}),
                }}
              >
                {place?.description || "-"}
              </Text>
            </Pressable>
          ))}
      </View>

      {(type === "textarea" || isNumeric) && !isWeb && (
        <InputAccessoryView nativeID={inputAccessoryViewID}>
          <Pressable
            onPress={() => Keyboard.dismiss()}
            style={{
              ...Style.containerRow,
              justifyContent: "flex-end",
              backgroundColor: Palette.transparentPrimary,
              padding: gutters,
              paddingVertical: gutters / 2,
            }}
          >
            <Text
              style={{
                ...Fonts({ color: Palette.primary }),
              }}
            >
              Fermer
            </Text>
          </Pressable>
        </InputAccessoryView>
      )}
    </>
  );
};

export { Input };
