import {
  View,
  Keyboard,
  TouchableWithoutFeedback,
  Dimensions,
  Animated,
  useWindowDimensions,
  Image as NativeImage,
} from "react-native";
import React, { useState, useCallback } from "react";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTailwind } from "tailwind-rn";
import PasswordLogin from "./PasswordLogin";
import PhoneNumLogin from "./PhoneNumLogin";
import { TabView, SceneMap, TabBar } from "react-native-tab-view";

export default function Login() {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //tab组件相关
  const layout = useWindowDimensions();
  const [index, setIndex] = useState(0);
  const [routes] = useState([
    { key: "phoneNumLogin", title: "验证码登录" },
    { key: "passwordLogin", title: "账号密码登录" },
  ]);

  const renderScene = useCallback(
    SceneMap({
      phoneNumLogin: () => <PhoneNumLogin />,
      passwordLogin: () => <PasswordLogin />,
    }),
    []
  );

  const renderIndicator = useCallback((props) => {
    const { position, navigationState, getTabWidth } = props;
    const inputRange = [0, 1];
    const translateX = position.interpolate({
      inputRange: inputRange,
      outputRange: inputRange.map((x) => {
        return x * getTabWidth(navigationState.index);
      }),
    });
    return (
      <Animated.View
        style={{
          width: `${100 / navigationState.routes.length}%`,
          transform: [
            {
              translateX,
            },
          ],
          paddingBottom: 5,
          ...tailwind("flex flex-1 items-center justify-end"),
        }}
      >
        <NativeImage
          source={require("../../assets/icon/others/tabindicator.png")}
        />
      </Animated.View>
    );
  }, []);

  const renderTabBar = useCallback(
    (props) => (
      <View style={tailwind("flex flex-row items-center")}>
        <TabBar
          {...props}
          activeColor="#FFFFFF"
          inactiveColor="#FFFFFF80"
          style={tailwind("bg-transparent flex-1")}
          labelStyle={tailwind("text-xl font-medium")}
          renderIndicator={renderIndicator}
        />
      </View>
    ),
    []
  );

  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <View
        style={{
          paddingTop: insets.top,
          paddingBottom: insets.bottom,
          paddingLeft: insets.left,
          paddingRight: insets.right,
          ...tailwind("flex flex-1"),
        }}
      >
        <TabView
          navigationState={{ index, routes }}
          swipeEnabled={true}
          renderScene={renderScene}
          renderTabBar={renderTabBar}
          onIndexChange={setIndex}
          initialLayout={{ width: layout.width }}
          style={tailwind("mt-32")}
        />
      </View>
    </TouchableWithoutFeedback>
  );
}
