/**
 * 新充电流程：正在充电模块
 * @邠心vbe on 2023/06/20
 */
import React, { useEffect, useRef, useState } from 'react';
import { Animated, Easing, Image, ScrollView, StyleSheet, Text, View } from 'react-native';
import Button, { ElevationObject } from '../../components/Button';
import utils from '../../utils/utils';
import { PaymentList } from '../chargeV2/Payment';

const StepCharging = ({
  connectorInfo={},
  currentPayment,
  curerntPerUse,
  onStopCharge
}) => {
  const [isCharging, setCharging] = useState(false);
  const [loadingEmps, setEmps] = useState("");
  const [skipAnim, setAnimSkip] = useState(false);
  const topAnim = useRef(new Animated.Value($vw(16)*-2)).current;
  const fadeAnim = useRef(new Animated.Value(0)).current;

  const moveTop = () => {
    fadeAnim.setValue(0);
    Animated.timing(topAnim, {
      toValue: ($vh(50) * -1 - $vw(16) - 32),
      duration: 1000,
      easing: Easing.linear,
      useNativeDriver: false
    }).start();
    setTimeout(() => {
      setCharging(true);
      showFade();
    }, 1100);
  }

  const showFade = () => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: false
    }).start();
    setTimeout(() => {
      setAnimSkip(true);
    }, 1100);
  }

  useEffect(() => {
    const isCharge = (connectorInfo.status == "Charging");
    console.log("[useEffect]:start", isCharge, fadeAnim);
    setCharging(isCharge);
    setAnimSkip(isCharge);
    if (!isCharge) {
      changeEmps();
    }
  }, [])

  useEffect(() => {
    //console.log("[useEffect]:connectorInfo", connectorInfo.status);
    if (connectorInfo.status == "Charging") {
      if (!isCharging) {
        moveTop();
      }
    } else {
      setCharging(false)
    }
  }, [connectorInfo])

  useEffect(() => {
    //console.log("[useEffect]:loadingEmps", loadingEmps);
    if (connectorInfo.status == "Charging") {
      moveTop();
    } else {
      setTimeout(() => {
        changeEmps();
      }, 500);
    }
  }, [loadingEmps])

  const changeEmps = () => {
    let emp = loadingEmps;
    if (loadingEmps.length == 3) {
      emp = "";
    } else {
      emp += ".";
    }
    setEmps(emp);
  }

  return (
  isCharging
  ? <ScrollView
      style={ui.flex1}
      contentContainerStyle={$padding(16)}>
      <Animated.View style={{opacity: skipAnim ? 1 : fadeAnim}}>
        <View style={ui.center}>
          <Image
            style={styles.stepImage}
            resizeMode="contain"
            source={require('../../images/site/charging-status-charge.png')}/>
          <Text style={styles.stepTitle}>{$t('charging.statusCharging')}</Text>
          <Text style={styles.stepDesc}>{$t('charging.stepChargingDesc')}</Text>
          { connectorInfo.batteryPercent >= 0 &&
            <Text
              style={styles.socText}
              numberOfLines={1}>{connectorInfo.batteryPercent || "0"}%</Text>
          }
        </View>
        <View style={styles.infoRow}>
          <View style={skipAnim ? styles.infoCarded : styles.infoCard}>
            <Text style={styles.infoTitle}>{$t('charging.labelTimeElapsed')}</Text>
            <Text
              numberOfLines={1}
              ellipsizeMode="tail"
              style={styles.infoText}>{utils.minutes2HHMM(connectorInfo?.timeElapsed ?? 0)}</Text>
            <Text style={styles.infoDesc}></Text>
          </View>
          <View style={skipAnim ? styles.infoCarded : styles.infoCard}>
            <Text style={styles.infoTitle}>{$t('charging.labelTotalkWh')}</Text>
            <Text
              numberOfLines={1}
              ellipsizeMode="tail"
              style={styles.infoText}>{connectorInfo.totalKWhDelivered || "0"} kWh</Text>
            <Text style={styles.infoDesc}></Text>
          </View>
        </View>
        <View style={styles.infoRow}>
          <View style={skipAnim ? styles.infoCarded : styles.infoCard}>
            <Text style={styles.infoTitle}>{$t('charging.labelRate')}</Text>
            <Text
              style={styles.infoText}>{connectorInfo.rates || "S$0.00/kWh"}</Text>
            <Text
              style={styles.infoDesc}>({connectorInfo.userRates || "S$0.00/kWh"})</Text>
          </View>
          <View style={skipAnim ? styles.infoCarded : styles.infoCard}>
            <Text style={styles.infoTitle}>{$t('charging.labelTotalCharges')}</Text>
            <Text
              numberOfLines={1}
              ellipsizeMode="tail"
              style={styles.infoText}>{connectorInfo.totalCharges || "S$ 0.0"}</Text>
            <Text
              numberOfLines={1}
              ellipsizeMode="tail"
              style={styles.infoDesc}>({connectorInfo.userTotalCharges || "S$ 0.0"})</Text>
          </View>
        </View>
      </Animated.View>
      <EndView/>
      <Text style={styles.label}>{$t('charging.paymentMethod')}</Text>
      <PaymentList
        payType={currentPayment}
        payPerUse={curerntPerUse}
      />
      <Button
        style={styles.buttonView}
        text={$t('charging.btnStopCharging')}
        elevation={1.5}
        borderRadius={6}
        onClick={onStopCharge}/>
    </ScrollView>
  : <View style={ui.flex1}>
      <Animated.View style={[
        styles.content, {
          marginTop: topAnim
        }
      ]}>
        <Image
          style={styles.stepImage}
          resizeMode="contain"
          source={require('../../images/site/charging-status-ready.png')}/>
        <View style={ui.flexcc}>
          <Text style={styles.stepTitle}>{$t('charging.stepInitializing')}</Text>
          <Text style={[styles.stepTitle, {width: 30, marginRight: -10}]}>{loadingEmps}</Text>
        </View>
        <Text style={styles.stepDesc}>{$t('charging.stepInitializingDesc')}</Text>
      </Animated.View>
      <View style={styles.bottomView}>
        <Text style={styles.label}>{$t('charging.paymentMethod')}</Text>
        <PaymentList
          payType={currentPayment}
          payPerUse={curerntPerUse}
        />
        <View style={styles.buttonView}></View>
      </View>
    </View>
  );
}

export default StepCharging;

const styles = StyleSheet.create({
  content: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  stepImage: {
    width: $vw(70),
    height: $vw(16),
    margin: 16
  },
  stepTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colorAccent
  },
  stepDesc: {
    color: textPrimary,
    fontSize: 16,
    textAlign: 'center',
    ...$padding(0, 32, 48)
  },
  socText: {
    right: $vw(15),
    color: colorAccent,
    width: 60,
    marginRight: -8,
    fontSize: 24,
    fontWeight: 'bold',
    position: 'absolute',
    textAlign: 'center',
  },
  infoRow: {
    marginLeft: 16,
    marginBottom: 16,
    flexDirection: 'row'
  },
  infoCard: {
    flex: 1,
    padding: 12,
    borderRadius: 10,
    marginRight: 16,
    alignItems: 'center',
    //...ElevationObject(5),
    backgroundColor: colorLight
  },
  infoCarded: {
    flex: 1,
    padding: 12,
    borderRadius: 10,
    marginRight: 16,
    alignItems: 'center',
    ...ElevationObject(5),
    backgroundColor: colorLight
  },
  infoTitle: {
    color: textPrimary,
    fontSize: 12,
    paddingTop: 1
  },
  infoText: {
    color: textPrimary,
    fontSize: 16,
    fontWeight: 'bold',
    ...$padding(16)
  },
  infoDesc: {
    color: textPrimary,
    fontSize: 12,
    marginTop: -16,
    paddingBottom: 8
  },
  infoStatus: {
    fontSize: 16,
    fontWeight: 'bold',
    ...$padding(16, 8)
  },label: {
    color: '#000',
    fontSize: 14,
    fontWeight: 'bold',
    paddingTop: 16,
    paddingBottom: 8
  },
  bottomView: {
    left: 0,
    right: 0,
    bottom: 32,
    padding: 16,
    position: 'absolute'
  },
  buttonView: {
    marginTop: 16,
    marginBottom: 16
  }
})