import React, { useState, useEffect, useRef } from 'react';
import { View, StyleSheet, ScrollView, Image, TouchableOpacity, Modal, Text, ImageBackground, Platform, NativeModules, Linking } from 'react-native';
import { TopNavigation, TopNavigationAction, Icon, Button } from '@ui-kitten/components';
import { apiService } from '../../utils/api';
import { rpx } from '../../utils/rpx';
import RNFS from 'react-native-fs';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { captureRef } from 'react-native-view-shot';
import Toast from 'react-native-toast-message';

const BackIcon = (props: any) => (
  <Icon {...props} name='arrow-back' />
);

const HelpCenterPage = ({ navigation }: { navigation: any }) => {
  const [showQrcode, setShowQrcode] = useState(false);
  const [phone, setPhone] = useState({ serverWx: '', serverPhone: '' });
  const [classifyList, setClassifyList] = useState([]);
  const [wordlist, setWordlist] = useState([]);
  const [tabindex, setTabindex] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const qrRef = useRef();

  useEffect(() => {
    const initData = async () => {
      try {
        setIsLoading(true);
        const classifyResponse = await apiService.getClassifyList();
        console.log('分类数据:', classifyResponse);
        
        if (classifyResponse?.data?.length > 0) {
          setClassifyList(classifyResponse.data);
          const firstClassifyId = classifyResponse.data[0].classifyId;
          console.log('第一个分类ID:', firstClassifyId);
          
          const articleResponse = await apiService.getArticleList(firstClassifyId);
          console.log('文章列表数据:', articleResponse);
          
          if (articleResponse?.rows) {
            setWordlist(articleResponse.rows);
          }
        }
      } catch (error) {
        console.error('初始化数据失败:', error);
        setClassifyList([]);
        setWordlist([]);
      } finally {
        setIsLoading(false);
      }
    };
    
    initData();
    fetchPhone();
  }, []);

  const navigateBack = () => {
    navigation.goBack();
  };

  const BackAction = () => (
    <TopNavigationAction icon={BackIcon} onPress={navigateBack} />
  );

  const fetchPhone = async () => {
    const response = await apiService.getServerPhone();
    setPhone(response.data);
  };

  const fetchArticleList = async (id: string) => {
    if (!id) return;
    
    try {
      setIsLoading(true);
      console.log('获取文章列表，分类ID:', id);
      const response = await apiService.getArticleList(id);
      console.log('获取到的文章列表:', response);
      
      if (response?.rows) {
        setWordlist(response.rows);
      } else {
        setWordlist([]);
      }
    } catch (error) {
      console.error('获取文章列表失败:', error);
      setWordlist([]);
    } finally {
      setIsLoading(false);
    }
  };

  const showWechat = () => {
    setShowQrcode(true);
  };

  const callPhone = () => {
    const phoneNumber = phone.serverPhone;
    if (phoneNumber) {
      Linking.openURL(`tel:${phoneNumber}`).catch(err => 
        console.error('拨打电话失败:', err)
      );
    } else {
      showToast('电话号码无效', 'error');
    }
  };

  const changeTab = (index: number, id: string) => {
    setTabindex(index);
    fetchArticleList(id);
  };

  const topage = (item: any) => {
    navigation.navigate('XmlRenderPage', { id: item.articleId });
  };

  const renderWordList = () => {
    console.log('当前wordlist数据:', wordlist);
    
    if (isLoading) {
      return (
        <View style={styles.wordListContainer}>
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      );
    }

    if (!Array.isArray(wordlist) || wordlist.length === 0) {
      return (
        <View style={styles.wordListContainer}>
          <Text style={styles.emptyText}>暂无数据</Text>
        </View>
      );
    }

    return (
      <View style={styles.wordListContainer}>
        {wordlist.map((item, index) => {
          console.log('渲染列表项:', item.title);
          return (
            <TouchableOpacity 
              key={item.articleId || index} 
              style={[
                styles.qsLi,
                index == wordlist.length - 1 && styles.lastQsLi
              ]} 
              onPress={() => topage(item)}
            >
              <Text style={styles.qsLiTxt} numberOfLines={1} ellipsizeMode="tail">
                {item.title || '无标题'}
              </Text>
              <Icon name='arrow-forward' style={styles.icon} />
            </TouchableOpacity>
          );
        })}
      </View>
    );
  };

  const saveWechatQrcode = async () => {
    try {
      const writePermission = await request(
        Platform.select({
          android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
          default: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
        })
      );

      if (writePermission !== RESULTS.GRANTED) {
        showToast('请在设置中授予存储权限', 'error');
        return;
      }

      const fileName = `wechat_qrcode_${Date.now()}.jpg`;
      const tempPath = `${RNFS.CachesDirectoryPath}/${fileName}`;

      const uri = await captureRef(qrRef, {
        format: 'jpg',
        quality: 1,
        result: 'base64',
      });

      await RNFS.writeFile(tempPath, uri, 'base64');

      await Promise.race([
        new Promise((resolve, reject) => {
          NativeModules.MediaScanner.scanFile(
            tempPath,
            'image/jpeg',
            (error) => {
              if (error) {
                console.warn('MediaScanner warning:', error);
                resolve(true);
              } else {
                resolve(true);
              }
            }
          );
        }),
        new Promise((resolve) => setTimeout(resolve, 3000))
      ]);

      showToast('二维码已保存到相册', 'success');
      setShowQrcode(false); // 确保遮罩关闭

      RNFS.unlink(tempPath).catch(e => {
        console.warn('清理临时文件失败:', e);
      });

    } catch (error) {
      console.error('Save error:', error);
      showToast('文件可能已保存到相册，请检查', 'info');
    }
  };

  const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
    Toast.show({
      type,
      text1: message,
      position: 'top',
      topOffset: Platform.OS === 'ios' ? 60 : 20,
      visibilityTime: 2000,
    });
  };

  return (
    <ImageBackground
      source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uYRs7Cv2Pbp95w3KjGO3' }}
      style={styles.background}
    >
      <View style={styles.container}>
        <TopNavigation
          title='帮助中心'
          alignment='center'
          accessoryLeft={BackAction}
          style={styles.navbar}
        />
        <ScrollView>
          <View style={styles.content}>
            <View style={styles.helpTime}>
              <View style={styles.helpTimeLeft}>
                <Text style={styles.helpTimeLeftTit}>Hi~有什么可以帮您！</Text>
                <Text style={[styles.helpTimeLeftContent, { marginTop: rpx(28) }]}>工作时间:</Text>
                <Text style={[styles.helpTimeLeftContent, { marginTop: rpx(10) }]}>工作日8:30-11:30 13:30-18:00</Text>
              </View>
              <View style={styles.helpTimeRight}>
                <Image 
                  source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uD8eJCmet0KN1WOEJBKZ' }} 
                  style={styles.helpTimeRightImg} 
                />
              </View>
            </View>

            <View style={styles.helpBtnBox}>
              <TouchableOpacity style={styles.helpBtnItem} onPress={showWechat}>
                <View style={styles.helpBtnItemLeft}>
                  <Text style={styles.helpBtnItemLeftTit}>微信客服</Text>
                  <Text style={styles.helpBtnItemLeftContent}>为您解答疑惑</Text>
                </View>
                <View style={styles.helpBtnItemRight}>
                  <Image 
                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uP0sux01iWvHzofugDjW' }} 
                    style={styles.helpBtnItemRightImg} 
                  />
                </View>
              </TouchableOpacity>

              <View style={styles.line}></View>

              <TouchableOpacity style={styles.helpBtnItem} onPress={callPhone}>
                <View style={styles.helpBtnItemLeft}>
                  <Text style={styles.helpBtnItemLeftTit}>客服电话</Text>
                  <Text style={styles.helpBtnItemLeftContent}>欢迎您拨打提问</Text>
                </View>
                <View style={styles.helpBtnItemRight}>
                  <Image 
                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uKt6yZ7lMykYci7yITT5' }} 
                    style={styles.helpBtnItemRightImg} 
                  />
                </View>
              </TouchableOpacity>
            </View>

            <View style={styles.qscard}>
              <View style={styles.cardTop}>
                {classifyList.map((item, index) => (
                  <TouchableOpacity 
                    key={item.classifyId || index} 
                    style={styles.li} 
                    onPress={() => changeTab(index, item.classifyId)}
                  >
                    <Text style={styles.txt}>{item.classifyName}</Text>
                    <View style={[styles.botBor, tabindex === index && styles.botBorActive]}></View>
                  </TouchableOpacity>
                ))}
              </View>
              <View style={styles.wordListWrapper}>
                {renderWordList()}
              </View>
            </View>
          </View>
        </ScrollView>

        <Modal visible={showQrcode} transparent={true} animationType="fade">
          <TouchableOpacity 
            style={styles.mask} 
            activeOpacity={1} 
            onPress={() => setShowQrcode(false)}
          >
            <View style={styles.qrcodeBox} >
              <Text style={styles.qrcodeTitle}>微信客服</Text>
              <Image source={{ uri: phone.serverWx }} style={styles.qrcodeImg} ref={qrRef}/>
              <TouchableOpacity style={styles.qrcodeBtn} onPress={saveWechatQrcode}>
                <Text style={styles.qrcodeBtnText}>保存二维码</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                style={styles.closeBtn} 
                onPress={() => setShowQrcode(false)}
              >
                <Text style={styles.closeBtnText}>×</Text>
              </TouchableOpacity>
            </View>
          </TouchableOpacity>
        </Modal>
      </View>
      <Toast />
    </ImageBackground>
  );
};

const styles = StyleSheet.create({
  wordListWrapper: {
    flex: 1,
    width: '100%',
  },
  background: {
    flex: 1,
  },
  container: {
    flex: 1,
  },
  navbar: {
    backgroundColor: 'transparent',
    height: rpx(90),
  },
  content: {
    paddingLeft: rpx(40),
    paddingRight: rpx(64),
  },
  helpTime: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  helpTimeLeft: {
    marginLeft: rpx(40),
  },
  helpTimeLeftTit: {
    fontWeight: '700',
    fontSize: rpx(36),
    color: '#3D3D3D',
  },
  helpTimeLeftContent: {
    fontWeight: '400',
    fontSize: rpx(24),
    color: '#3D3D3D',
  },
  helpTimeRight: {
    justifyContent: 'center',
  },
  helpTimeRightImg: {
    width: rpx(168),
    height: rpx(154),
  },
  helpBtnBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: rpx(50),
    width: rpx(644),
    padding: rpx(20),
    paddingHorizontal: rpx(38),
    backgroundColor: '#FFFFFF',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: rpx(6) },
    shadowOpacity: 0.08,
    shadowRadius: rpx(64),
    borderRadius: rpx(20),
  },
  helpBtnItem: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  helpBtnItemLeft: {},
  helpBtnItemLeftTit: {
    fontWeight: '700',
    fontSize: rpx(28),
    color: '#3D3D3D',
  },
  helpBtnItemLeftContent: {
    marginTop: rpx(14),
    fontWeight: '400',
    fontSize: rpx(24),
    color: '#3D3D3D',
  },
  helpBtnItemRight: {},
  helpBtnItemRightImg: {
    width: rpx(84),
    height: rpx(84),
  },
  line: {
    marginHorizontal: rpx(20),
    width: rpx(2),
    height: rpx(128),
    backgroundColor: '#D8D8D8',
  },
  qscard: {
    width: rpx(680),
    marginVertical: rpx(40),
    backgroundColor: '#FFFFFF',
    borderRadius: rpx(40),
    padding: rpx(28),
    paddingHorizontal: rpx(30),
    shadowColor: '#2A82E4',
    shadowOffset: { width: 0, height: rpx(16) },
    shadowOpacity: 0.1,
    shadowRadius: rpx(40),
  },
  cardTop: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'nowrap',
  },
  li: {
    minWidth: rpx(112),
    marginRight: rpx(20),
  },
  txt: {
    width: rpx(150),
    fontWeight: '500',
    fontSize: rpx(28),
    color: '#3D3D3D',
    zIndex: 1,
  },
  botBor: {
    marginTop: rpx(-20),
    width: '90%',
    height: rpx(26),
    backgroundColor: '#FFFFFF',
    borderRadius: rpx(20),
    zIndex: 0,
  },
  botBorActive: {
    backgroundColor: 'rgba(66, 151, 243, 0.55)',
  },
  wordListContainer: {
    marginTop: rpx(20),
    paddingHorizontal: rpx(20),
  },
  qsLi: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderBottomWidth: rpx(2),
    borderBottomColor: 'rgba(216, 216, 216, 0.44)',
    paddingVertical: rpx(26),
  },
  lastQsLi: {
    borderBottomWidth: rpx(2),
    borderBottomColor: '#FFFFFF',
  },
  qsLiTxt: {
    flex: 1,
    fontWeight: '400',
    fontSize: rpx(28),
    color: '#3D3D3D',
    marginRight: rpx(20),
  },
  icon: {
    width: rpx(32),
    height: rpx(32),
  },
  txtActive: {
    color: '#4297F3',
    fontWeight: '500',
  },
  mask: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  qrcodeBox: {
    width: rpx(600),
    backgroundColor: '#FFFFFF',
    borderRadius: rpx(20),
    padding: rpx(40),
    position: 'relative',
  },
  qrcodeTitle: {
    fontSize: rpx(32),
    fontWeight: '500',
    textAlign: 'center',
    marginBottom: rpx(30),
    color: '#333',
  },
  qrcodeImg: {
    width: rpx(400),
    height: rpx(450),
    alignSelf: 'center',
  },
  qrcodeBtn: {
    width: rpx(400),
    height: rpx(80),
    backgroundColor: '#4297F3',
    borderRadius: rpx(40),
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: rpx(40),
    alignSelf: 'center',
  },
  qrcodeBtnText: {
    color: '#FFFFFF',
    fontSize: rpx(28),
  },
  closeBtn: {
    position: 'absolute',
    right: rpx(20),
    top: rpx(20),
    width: rpx(60),
    height: rpx(60),
    justifyContent: 'center',
    alignItems: 'center',
  },
  closeBtnText: {
    fontSize: rpx(40),
    color: '#999',
  },
  loadingText: {
    textAlign: 'center',
    padding: rpx(20),
    color: '#666',
    fontSize: rpx(28),
  },
  emptyText: {
    textAlign: 'center',
    padding: rpx(20),
    color: '#999',
    fontSize: rpx(28),
  },
});

export default HelpCenterPage;