import 'package:autosos_flutter/provider/providers.dart';
import 'package:autosos_flutter/util/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

/// 提现申请页（对应 Android TiXianActivity）
class WithdrawalPage extends ConsumerStatefulWidget {
  const WithdrawalPage({super.key});

  @override
  ConsumerState<WithdrawalPage> createState() => _WithdrawalPageState();
}

class _WithdrawalPageState extends ConsumerState<WithdrawalPage> {
  final _amount = TextEditingController();
  final _realName = TextEditingController();
  final _bankAccount = TextEditingController();
  bool _loading = false;
  double _balance = 0;

  @override
  void initState() {
    super.initState();
    _load();
  }

  @override
  void dispose() {
    _amount.dispose();
    _realName.dispose();
    _bankAccount.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    final resp = await ref.read(userApiProvider).info();
    if (!mounted || !resp.isSuccess || resp.data == null) return;
    final u = resp.data!;
    setState(() {
      _balance = u.balance ?? 0;
      _realName.text = u.realName ?? '';
    });
  }

  Future<void> _submit() async {
    final amount = double.tryParse(_amount.text.trim());
    if (amount == null || amount <= 0) {
      Toast.error('请输入提现金额');
      return;
    }
    if (amount > _balance) {
      Toast.error('提现金额不能超过余额');
      return;
    }
    if (_realName.text.isEmpty) {
      Toast.error('请填写收款人姓名');
      return;
    }
    if (_bankAccount.text.isEmpty) {
      Toast.error('请填写银行卡号');
      return;
    }
    setState(() => _loading = true);
    EasyLoading.show(status: '提交中…');
    try {
      final r = await ref.read(userApiProvider).applyWithdrawal(
            amount: amount,
            bankAccount: _bankAccount.text.trim(),
            realName: _realName.text.trim(),
          );
      EasyLoading.dismiss();
      if (!r.isSuccess) {
        Toast.error(r.message ?? '提现失败');
        return;
      }
      Toast.success('提现申请已提交');
      if (mounted) context.pop(true);
    } catch (e) {
      EasyLoading.dismiss();
      Toast.error('提现异常：$e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('提现')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.red.shade400, Colors.red.shade700],
                ),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '可提现余额（元）',
                    style: TextStyle(color: Colors.white70),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '¥${_balance.toStringAsFixed(2)}',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 32,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),
            TextField(
              controller: _amount,
              keyboardType:
                  const TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
              ],
              decoration: const InputDecoration(
                labelText: '提现金额',
                prefixText: '¥ ',
                border: OutlineInputBorder(),
              ),
              style: const TextStyle(
                fontSize: 24,
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 4),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton(
                onPressed: () => _amount.text = _balance.toStringAsFixed(2),
                child: const Text('全部提现'),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _realName,
              decoration: const InputDecoration(
                labelText: '收款人姓名',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _bankAccount,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '银行卡号',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _loading ? null : _submit,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                minimumSize: const Size.fromHeight(48),
              ),
              child: Text(_loading ? '提交中…' : '确认提现'),
            ),
            const SizedBox(height: 12),
            const Text(
              '• 提现申请提交后，财务将在 1-3 个工作日内处理\n'
              '• 单笔最低 1 元，最高 50000 元\n'
              '• 如有问题请联系客服',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
