import {
  View,
  Text,
  ScrollView,
  ActivityIndicator,
  TextInput,
} from "react-native";
import React, { useState } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import { Button, Divider, CheckBox, Switch } from "@rneui/themed";

export default function SpacePaymentSetting({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  const data = route.params.data;

  const [isSubmitting, setIsSubmitting] = useState(false);

  //解锁空间价格
  const [spacePrice, setSpacePrice] = useState(
    (data?.admission_price / 100).toString()
  );

  //铁粉价格
  const [ironFanPrice, setIronFanPrice] = useState(
    (data?.ironfanship_price / 100).toString()
  );

  //启用超粉功能
  const [isSuperFanOn, setIsSuperFanOn] = useState(
    data?.is_superfanship_enabled === 1 ? true : false
  );

  //超粉价格
  const [superFanPrice, setSuperFanPrice] = useState(
    (data?.superfanship_price / 100).toString()
  );

  //超粉单次开通有效期
  const [superFanExpiration, setSuperFanExpiration] = useState(
    data?.superfanship_valid_period
  );

  //是否开通超粉送微信
  const [unlockWechat, setUnlockWechat] = useState(
    data?.is_superfanship_give_wechat === 1 ? true : false
  );

  const handleSubmit = async () => {
    if (!spacePrice || !ironFanPrice) {
      Toast.show({
        type: "error",
        text1: "请完善内容后提交",
        topOffset: 60,
      });
      return;
    }
    if (isSuperFanOn && !superFanPrice) {
      Toast.show({
        type: "error",
        text1: "请填写超粉价格",
        topOffset: 60,
      });
      return;
    }
    const _spacePrice = parseInt(spacePrice * 100, 10);
    if (isNaN(_spacePrice) || _spacePrice < 0) {
      Toast.show({
        type: "error",
        text1: "请输入有效的解锁空间价格",
        topOffset: 60,
      });
      return;
    }
    const _ironFanPrice = parseInt(ironFanPrice * 100, 10);
    if (isNaN(_ironFanPrice) || _ironFanPrice < 100 || _ironFanPrice > 388800) {
      Toast.show({
        type: "error",
        text1: "请输入有效的铁粉价格",
        topOffset: 60,
      });
      return;
    }
    const _superFanPrice = parseInt(superFanPrice * 100, 10);
    if (
      isSuperFanOn &&
      (isNaN(_superFanPrice) || _superFanPrice < 100 || _superFanPrice > 388800)
    ) {
      Toast.show({
        type: "error",
        text1: "请输入有效的超粉价格",
        topOffset: 60,
      });
      return;
    }
    if (isSuperFanOn && _superFanPrice <= _ironFanPrice) {
      Toast.show({
        type: "error",
        text1: "请输入大于铁粉价格的超粉价格",
        topOffset: 60,
      });
      return;
    }
    if (
      isSuperFanOn &&
      superFanExpiration !== 0 &&
      superFanExpiration !== 1 &&
      superFanExpiration !== 2 &&
      superFanExpiration !== 3 &&
      superFanExpiration !== 4
    ) {
      Toast.show({
        type: "error",
        text1: "请选择超粉有效期",
        topOffset: 60,
      });
      return;
    }

    if (isSubmitting) return;
    setIsSubmitting(true);

    const apiUrl = process.env.EXPO_PUBLIC_API_URL;

    try {
      const base = await baseRequest();
      const body = {
        id: data.id,
        admission_price: parseInt(spacePrice * 100, 10),
        ironfanship_price: parseInt(ironFanPrice * 100, 10),
        is_superfanship_enabled: isSuperFanOn ? 1 : 0,
        superfanship_price: parseInt(superFanPrice * 100, 10),
        superfanship_valid_period: superFanExpiration,
        is_superfanship_give_wechat: unlockWechat ? 1 : 0,
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone/update?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      Toast.show({
        type: "success",
        text1: "修改成功，请重进空间刷新查看",
        topOffset: 60,
      });
      navigation.goBack();
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <ScrollView
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("p-4")}>
        <View style={tailwind("flex flex-row items-center justify-between")}>
          <Text style={tailwind("text-base font-medium text-white mt-4 mb-1")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>解锁空间价格
          </Text>
          <Text
            style={tailwind("text-sm font-medium text-[#FFFFFF80] mt-4 mb-1")}
          >
            ¥0~3888，仅支持整数
          </Text>
        </View>
        <TextInput
          value={spacePrice}
          onChangeText={(value) => setSpacePrice(value)}
          keyboardType="numeric"
          placeholder="解锁后可查看空间内免费动态"
          placeholderTextColor="#FFFFFF80"
          style={tailwind("text-white")}
          underlineColorAndroid="transparent"
          textAlign="top"
        />
        <Divider style={tailwind("my-2")} />
        <View style={tailwind("flex flex-row items-center justify-between")}>
          <Text style={tailwind("text-base font-medium text-white mt-4 mb-1")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>铁粉价格
          </Text>
          <Text
            style={tailwind("text-sm font-medium text-[#FFFFFF80] mt-4 mb-1")}
          >
            ¥1~3888，仅支持整数
          </Text>
        </View>
        <TextInput
          value={ironFanPrice}
          onChangeText={(value) => setIronFanPrice(value)}
          keyboardType="numeric"
          placeholder="解锁后可查看空间内铁粉专享动态"
          placeholderTextColor="#FFFFFF80"
          style={tailwind("text-white")}
          underlineColorAndroid="transparent"
          textAlign="top"
        />
        <Divider style={tailwind("my-2")} />
        <View
          style={tailwind(
            "flex flex-row items-center justify-between mt-4 mb-1"
          )}
        >
          <Text style={tailwind("text-base font-medium text-white")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>启用超粉功能
          </Text>
          <Switch
            value={isSuperFanOn}
            onValueChange={(value) => setIsSuperFanOn(value)}
            thumbColor="#ffffff"
            trackColor={{ true: "#FF669E", false: "#FFFFFF1A" }}
            style={tailwind("mx-1")}
          />
        </View>
        <Divider style={tailwind("my-2")} />
        {isSuperFanOn && (
          <View>
            <View
              style={tailwind("flex flex-row items-center justify-between")}
            >
              <Text
                style={tailwind("text-base font-medium text-white mt-4 mb-1")}
              >
                超粉价格
              </Text>
              <Text
                style={tailwind(
                  "text-sm font-medium text-[#FFFFFF80] mt-4 mb-1"
                )}
              >
                ¥1~3888，仅支持整数
              </Text>
            </View>
            <TextInput
              value={superFanPrice}
              onChangeText={(value) => setSuperFanPrice(value)}
              keyboardType="numeric"
              placeholder="最高身份，可查看空间所有动态"
              placeholderTextColor="#FFFFFF80"
              style={tailwind("text-white")}
              underlineColorAndroid="transparent"
              textAlign="top"
            />
            <Divider style={tailwind("my-2")} />
            <Text
              style={tailwind("text-base font-medium text-white mt-4 mb-1")}
            >
              超粉单次开通有效期
            </Text>
            <View style={tailwind("flex flex-row flex-wrap")}>
              <View style={tailwind("flex flex-row basis-1/3 items-center")}>
                <CheckBox
                  checked={superFanExpiration === 0}
                  onPress={() => setSuperFanExpiration(0)}
                  iconType="material-community"
                  checkedIcon="checkbox-marked"
                  uncheckedIcon="checkbox-blank-outline"
                  checkedColor="#FF669E"
                  containerStyle={tailwind("p-0 m-0 bg-transparent")}
                  size={18}
                />
                <Text
                  onPress={() => setSuperFanExpiration(0)}
                  style={tailwind("text-base font-medium text-white")}
                >
                  永久
                </Text>
              </View>
              <View style={tailwind("flex flex-row basis-1/3 items-center")}>
                <CheckBox
                  checked={superFanExpiration === 4}
                  onPress={() => setSuperFanExpiration(4)}
                  iconType="material-community"
                  checkedIcon="checkbox-marked"
                  uncheckedIcon="checkbox-blank-outline"
                  checkedColor="#FF669E"
                  containerStyle={tailwind("p-0 m-0 bg-transparent")}
                  size={18}
                />
                <Text
                  onPress={() => setSuperFanExpiration(4)}
                  style={tailwind("text-base font-medium text-white")}
                >
                  年度
                </Text>
              </View>
              <View style={tailwind("flex flex-row basis-1/3 items-center")}>
                <CheckBox
                  checked={superFanExpiration === 3}
                  onPress={() => setSuperFanExpiration(3)}
                  iconType="material-community"
                  checkedIcon="checkbox-marked"
                  uncheckedIcon="checkbox-blank-outline"
                  checkedColor="#FF669E"
                  containerStyle={tailwind("p-0 m-0 bg-transparent")}
                  size={18}
                />
                <Text
                  onPress={() => setSuperFanExpiration(3)}
                  style={tailwind("text-base font-medium text-white")}
                >
                  半年
                </Text>
              </View>
              <View
                style={tailwind("flex flex-row basis-1/3 items-center mt-2")}
              >
                <CheckBox
                  checked={superFanExpiration === 2}
                  onPress={() => setSuperFanExpiration(2)}
                  iconType="material-community"
                  checkedIcon="checkbox-marked"
                  uncheckedIcon="checkbox-blank-outline"
                  checkedColor="#FF669E"
                  containerStyle={tailwind("p-0 m-0 bg-transparent")}
                  size={18}
                />
                <Text
                  onPress={() => setSuperFanExpiration(2)}
                  style={tailwind("text-base font-medium text-white")}
                >
                  季度
                </Text>
              </View>
              <View
                style={tailwind("flex flex-row basis-1/3 items-center mt-2")}
              >
                <CheckBox
                  checked={superFanExpiration === 1}
                  onPress={() => setSuperFanExpiration(1)}
                  iconType="material-community"
                  checkedIcon="checkbox-marked"
                  uncheckedIcon="checkbox-blank-outline"
                  checkedColor="#FF669E"
                  containerStyle={tailwind("p-0 m-0 bg-transparent")}
                  size={18}
                />
                <Text
                  onPress={() => setSuperFanExpiration(1)}
                  style={tailwind("text-base font-medium text-white")}
                >
                  月度
                </Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind(
                "flex flex-row items-center justify-between mt-4 mb-1"
              )}
            >
              <Text style={tailwind("text-base font-medium text-white")}>
                开通超粉赠送微信
              </Text>
              <Switch
                value={unlockWechat}
                onValueChange={(value) => setUnlockWechat(value)}
                thumbColor="#ffffff"
                trackColor={{ true: "#FF669E", false: "#FFFFFF1A" }}
                style={tailwind("mx-1")}
              />
            </View>
            <Divider style={tailwind("my-2")} />
          </View>
        )}
        <Button
          color="#FF669E"
          radius="999"
          size="md"
          disabled={isSubmitting}
          disabledStyle={tailwind("bg-[#FFFFFF80]")}
          disabledTitleStyle={tailwind("text-white")}
          onPress={handleSubmit}
          titleStyle={tailwind("text-base")}
          containerStyle={tailwind("mt-4")}
        >
          {isSubmitting && <ActivityIndicator size="small" color="white" />}
          {isSubmitting ? "正在保存..." : "保存设置"}
        </Button>
      </View>
    </ScrollView>
  );
}
