import React, { useLayoutEffect, useState } from 'react';
import {
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
} from 'react-native';
import { StackScreenProps } from '@react-navigation/stack';
import { LoginParamList } from '@app/routes/login/LoginParamList.ts';
import { useCommon } from '@common/contexts/useCommon';
import { useEnv } from '@common/env/useEnv';
import ENV from '@common/env/env';
import { THEME_COLOR } from '@common/constants';
import { useQuickClicks } from '@szyx-mobile/hooks';
import Alert from '@common/components/Alert.tsx';
import { showErrorMessage, showMessage } from '@common/ToastHelper.ts';

const ITEM_COLOR_SELECTED = THEME_COLOR;
const ITEM_COLOR_UNSELECTED = '#FFFFFF';
const TEXT_COLOR_SELECTED = '#FFFFFF';
const TEXT_COLOR_UNSELECTED = '#11102C';

const DEFAULT_DISPLAY_NUMBER = 2; // 默认展示的环境的数量

type Props = StackScreenProps<LoginParamList, 'Environment'>;

export default function EnvironmentScreen(props: Props) {
  const {navigation} = props;

  useLayoutEffect(() => {
    navigation.setOptions({
      title: '环境切换',
    });
  }, [navigation]);

  const {
    actions: {save},
  } = useCommon();

  const {env} = useEnv();

  const [expanded, setExpanded] = useState(
    ENV.findIndex(item => item.env === env) >= DEFAULT_DISPLAY_NUMBER,
  ); // 是否展示所有环境（如果当前环境不在默认展示的环境中，则直接展示所有环境）
  const {click} = useQuickClicks(5, () => {
    setExpanded(true);
  });

  return (
    <ScrollView
      style={styles.scroll}
      contentInsetAdjustmentBehavior="scrollableAxes"
      scrollIndicatorInsets={{right: 1}}>
      <SafeAreaView>
        <Text
          style={styles.headerText}
          onPress={() => {
            click();
          }}>
          警告！此页面为环境切换页面，操作将会变更您的应用环境。若您无意进入此页面，请及时关闭，切勿因为误操作导致无法正常使用应用！
        </Text>
        {(expanded ? ENV : ENV.slice(0, DEFAULT_DISPLAY_NUMBER)).map(
          (envItem, index) => {
            return (
              <TouchableOpacity
                key={index}
                style={[
                  styles.item,
                  {
                    backgroundColor:
                      envItem.env === env
                        ? ITEM_COLOR_SELECTED
                        : ITEM_COLOR_UNSELECTED,
                  },
                ]}
                onPress={() => {
                  Alert.show(
                    `确定要切换到${envItem.title}吗？`,
                    undefined,
                    {
                      action: () => {
                        save('env', envItem.env)
                          .then(() => {
                            showMessage(`已切换到${envItem.title}`);
                            navigation.pop();
                          })
                          .catch(e => {
                            showErrorMessage('切换环境失败');
                            console.error(`环境切换失败：${e.message}`);
                          });
                      },
                    },
                    {},
                  );
                }}>
                <Text
                  style={[
                    styles.itemText,
                    {
                      color:
                        envItem.env === env
                          ? TEXT_COLOR_SELECTED
                          : TEXT_COLOR_UNSELECTED,
                    },
                  ]}>
                  {envItem.title}
                </Text>
                {/* 其余展示内容 */}
              </TouchableOpacity>
            );
          },
        )}
      </SafeAreaView>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scroll: {
    paddingVertical: 8,
  },
  headerText: {
    color: '#DD2222',
    marginVertical: 8,
    marginHorizontal: 16,
  },
  item: {
    backgroundColor: '#FFFFFF',
    marginVertical: 8,
    marginHorizontal: 16,
    padding: 8,
    borderRadius: 4,
  },
  itemText: {
    marginVertical: 4,
  },
});
