import { View, Text, Input } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { getWithdrawConfig, getWithdrawStats, applyWithdraw } from '@/api/shop/shopWithdrawRecord';
import PayModal from '@/components/business/PayModal';

import './index.scss';

definePageConfig({
  navigationBarTitleText: '提现',
});

export default function WithdrawPage() {
  const [config, setConfig] = useState<any>({});
  const [stats, setStats] = useState<any>({});
  const [amount, setAmount] = useState('');
  const [showPayModal, setShowPayModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    loadConfig();
    loadStats();
  }, []);

  const loadConfig = async () => {
    try {
      const res = await getWithdrawConfig();
      if (res.code === 200) {
        setConfig(res.data);
      }
    } catch (error) {
      console.error('加载配置失败', error);
    }
  };

  const loadStats = async () => {
    try {
      const res = await getWithdrawStats();
      if (res.code === 200) {
        setStats(res.data);
      }
    } catch (error) {
      console.error('加载统计失败', error);
    }
  };

  const handleWithdraw = () => {
    if (!amount || parseFloat(amount) <= 0) {
      Taro.showToast({ title: '请输入提现金额', icon: 'none' });
      return;
    }

    const amountNum = parseFloat(amount);
    const minAmount = parseFloat(config.withdraw_min_amount || '10');
    const maxAmount = parseFloat(config.withdraw_max_amount || '200');

    if (amountNum < minAmount) {
      Taro.showToast({ title: `最低提现金额为${minAmount}元`, icon: 'none' });
      return;
    }

    if (amountNum > maxAmount) {
      Taro.showToast({ title: `单次最大提现金额为${maxAmount}元`, icon: 'none' });
      return;
    }

    setShowPayModal(true);
  };

  const handlePayConfirm = async (payType: number) => {
    setShowPayModal(false);
    if (payType !== 0) return; // 0微信支付

    setSubmitting(true);
    try {
      const res = await applyWithdraw({ amount: parseFloat(amount) });
      if (res.code === 200) {
        Taro.showToast({ title: '提现申请已提交', icon: 'success' });
        setTimeout(() => {
          Taro.navigateBack();
        }, 1500);
      } else {
        Taro.showToast({ title: res.message || '提交失败', icon: 'none' });
      }
    } catch (error) {
      console.error('提现申请失败', error);
      Taro.showToast({ title: '提交失败', icon: 'none' });
    } finally {
      setSubmitting(false);
    }
  };

  const handleAllWithdraw = () => {
    // 可提现余额
    const available = stats.withdrawingTotal || '0';
    setAmount(available);
  };

  return (
    <View className="withdraw-page">
      <View className="withdraw-card">
        <View className="card-title">提现金额</View>

        <View className="amount-input-wrap">
          <Text className="currency-symbol">¥</Text>
          <Input
            className="amount-input"
            type="digit"
            placeholder="请输入提现金额"
            value={amount}
            onInput={(e) => setAmount(e.detail.value)}
          />
        </View>

        <View className="amount-tips">
          <Text>可提现佣金: ¥{stats.withdrawingTotal || '0.00'}</Text>
          <Text className="all-withdraw" onClick={handleAllWithdraw}>
            全部提现
          </Text>
        </View>

        {config.withdraw_fee_rate && parseFloat(config.withdraw_fee_rate) > 0 && (
          <View className="fee-tips">
            手续费: {config.withdraw_fee_rate}%
          </View>
        )}
      </View>

      <View className="config-card">
        <View className="config-item">
          <Text className="config-label">单次限额</Text>
          <Text className="config-value">¥{config.withdraw_max_amount || '200'}</Text>
        </View>
        <View className="config-item">
          <Text className="config-label">每日限额</Text>
          <Text className="config-value">¥{config.withdraw_daily_limit || '2000'}</Text>
        </View>
        {config.withdraw_time_start && (
          <View className="config-item">
            <Text className="config-label">提现时间</Text>
            <Text className="config-value">
              {config.withdraw_time_start} - {config.withdraw_time_end}
            </Text>
          </View>
        )}
      </View>

      <View
        className={`submit-btn ${amount && !submitting ? '' : 'disabled'}`}
        onClick={handleWithdraw}
      >
        {submitting ? '提交中...' : '确认提现'}
      </View>

      <PayModal
        visible={showPayModal}
        amount={parseFloat(amount) || 0}
        onConfirm={handlePayConfirm}
        onClose={() => setShowPayModal(false)}
      />
    </View>
  );
}
