import React, { useEffect, useState } from 'react';
import { Card, Form, InputNumber, Button, message, Spin, Divider } from 'antd';
import { getServiceFeeConfig, updateServiceFeeConfig, getWithdrawConfig, updateMerchantMinWithdrawAmount, updatePlatformMinWithdrawAmount } from '@/api/config';
import StorageSettings from './StorageSettings';

const SystemSettings: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [savingWithdraw, setSavingWithdraw] = useState(false);
  const [form] = Form.useForm();
  const [withdrawForm] = Form.useForm();

  const fetchConfig = async () => {
    setLoading(true);
    try {
      const [feeRes, withdrawRes]: any = await Promise.all([
        getServiceFeeConfig(),
        getWithdrawConfig(),
      ]);
      form.setFieldsValue({ serviceFeeRate: feeRes.data?.rate || 0.05 });
      withdrawForm.setFieldsValue({
        merchantMinWithdrawAmount: withdrawRes.data?.merchantMinWithdrawAmount || 100,
        platformMinWithdrawAmount: withdrawRes.data?.platformMinWithdrawAmount || 10,
      });
    } catch (e) {
      form.setFieldsValue({ serviceFeeRate: 0.05 });
      withdrawForm.setFieldsValue({
        merchantMinWithdrawAmount: 100,
        platformMinWithdrawAmount: 10,
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchConfig(); }, []);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);
      await updateServiceFeeConfig(values.serviceFeeRate);
      message.success('服务费配置已保存');
      fetchConfig();
    } catch (e: any) {
      if (e?.message) message.error(e.message);
    } finally {
      setSaving(false);
    }
  };

  const handleSaveWithdraw = async () => {
    try {
      const values = await withdrawForm.validateFields();
      setSavingWithdraw(true);
      await Promise.all([
        updateMerchantMinWithdrawAmount(values.merchantMinWithdrawAmount),
        updatePlatformMinWithdrawAmount(values.platformMinWithdrawAmount),
      ]);
      message.success('提现配置已保存');
      fetchConfig();
    } catch (e: any) {
      if (e?.message) message.error(e.message);
    } finally {
      setSavingWithdraw(false);
    }
  };

  if (loading) return <Spin size="large" style={{ display: 'block', marginTop: 100 }} />;

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>系统设置</h2>

      <Card title="服务费配置" style={{ maxWidth: 600, marginBottom: 24 }}>
        <Form form={form} layout="vertical">
          <Form.Item
            label="软件服务费比例"
            name="serviceFeeRate"
            rules={[
              { required: true, message: '请输入服务费比例' },
              { type: 'number', min: 0, max: 1, message: '比例必须在0-1之间' },
            ]}
            extra="用户支付金额中，该比例将作为软件服务费归平台所有，剩余部分为商家预计收入"
          >
            <InputNumber
              min={0}
              max={1}
              step={0.01}
              precision={4}
              style={{ width: '100%' }}
              formatter={(v) => `${(Number(v) * 100).toFixed(2)}%`}
              parser={(v) => Number(v?.replace('%', '')) / 100 as any}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" loading={saving} onClick={handleSave}>
              保存配置
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <div style={{ color: '#666', fontSize: 14 }}>
          <p><strong>计算公式：</strong></p>
          <p>软件服务费 = 实付金额 × 服务费比例</p>
          <p>商家预计收入 = 实付金额 - 软件服务费</p>
          <p style={{ marginTop: 12 }}>
            <strong>示例：</strong>实付金额 ¥100.00，服务费比例 5%
          </p>
          <p>软件服务费 = ¥5.00，商家预计收入 = ¥95.00</p>
        </div>
      </Card>

      <Card title="提现配置" style={{ maxWidth: 600, marginBottom: 24 }}>
        <Form form={withdrawForm} layout="vertical">
          <Form.Item
            label="商家提现最低金额"
            name="merchantMinWithdrawAmount"
            rules={[
              { required: true, message: '请输入商家提现最低金额' },
              { type: 'number', min: 0, message: '金额不能为负数' },
            ]}
            extra="商家申请提现时的最低金额限制"
          >
            <InputNumber
              min={0}
              step={10}
              precision={2}
              style={{ width: '100%' }}
              addonAfter="元"
            />
          </Form.Item>
          <Form.Item
            label="平台提现最低金额"
            name="platformMinWithdrawAmount"
            rules={[
              { required: true, message: '请输入平台提现最低金额' },
              { type: 'number', min: 0, message: '金额不能为负数' },
            ]}
            extra="平台账户申请提现时的最低金额限制"
          >
            <InputNumber
              min={0}
              step={10}
              precision={2}
              style={{ width: '100%' }}
              addonAfter="元"
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" loading={savingWithdraw} onClick={handleSaveWithdraw}>
              保存配置
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <div style={{ color: '#666', fontSize: 14 }}>
          <p><strong>说明：</strong></p>
          <p>• 商家提现：商家在商家后台申请提现时，提现金额必须大于等于设置的最低金额</p>
          <p>• 平台提现：平台管理员在平台后台申请提现时，提现金额必须大于等于设置的最低金额</p>
          <p>• 用户提现：用户提现最低金额由邀请活动配置中的"提现门槛"控制</p>
        </div>
      </Card>

      <StorageSettings />
    </div>
  );
};

export default SystemSettings;