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

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

  const fetchConfig = async () => {
    setLoading(true);
    try {
      const res: any = await getServiceFeeConfig();
      form.setFieldsValue({ serviceFeeRate: res.data?.rate || 0.05 });
    } catch (e) {
      form.setFieldsValue({ serviceFeeRate: 0.05 });
    } 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);
    }
  };

  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>

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

export default SystemSettings;