import React, { useState, useEffect } from 'react';
import { Card, Table, DatePicker, Space, Tag, Button, Statistic, Row, Col, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { getFinancialOverview, getMerchantTransactions } from '@/api/finance';
import type { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;

interface ServiceFeeRecord {
  id: number;
  orderId: number;
  orderNo: string;
  merchantName: string;
  userName: string;
  orderAmount: number;
  commissionRate: number;
  commissionAmount: number;
  status: string;
  settledAt: string;
  createdAt: string;
}

const ServiceFees: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<ServiceFeeRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
  const [statistics, setStatistics] = useState({
    todayCommission: 0,
    monthCommission: 0,
    totalCommission: 0,
    pendingCommission: 0,
  });

  useEffect(() => {
    fetchStatistics();
    fetchData();
  }, []);

  const fetchStatistics = async () => {
    try {
      const res = await getFinancialOverview({});
      if (res?.data) {
        setStatistics({
          todayCommission: res.data?.todayCommission || 0,
          monthCommission: res.data?.monthCommission || 0,
          totalCommission: res.data?.totalCommission || 0,
          pendingCommission: res.data?.pendingCommission || 0,
        });
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  const fetchData = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        pageSize,
      };

      if (dateRange && dateRange[0] && dateRange[1]) {
        params.startDate = dateRange[0].format('YYYY-MM-DD');
        params.endDate = dateRange[1].format('YYYY-MM-DD');
      }

      const res = await getMerchantTransactions(params);
      if (res?.data) {
        setDataSource(res.data?.list || []);
        setPagination({
          current: page,
          pageSize,
          total: res.data?.total || 0,
        });
      }
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (newPagination: any) => {
    fetchData(newPagination.current, newPagination.pageSize);
  };

  const handleDateChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
    setDateRange(dates);
  };

  const handleSearch = () => {
    fetchData(1, pagination.pageSize);
  };

  const handleExport = () => {
    message.info('导出功能开发中');
  };

  const columns: ColumnsType<ServiceFeeRecord> = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '商家名称',
      dataIndex: 'merchantName',
      key: 'merchantName',
      width: 150,
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 120,
      render: (amount: number) => `¥${formatMoney(amount)}`,
    },
    {
      title: '佣金比例',
      dataIndex: 'commissionRate',
      key: 'commissionRate',
      width: 100,
      render: (rate: number) => `${(rate * 100).toFixed(1)}%`,
    },
    {
      title: '佣金金额',
      dataIndex: 'commissionAmount',
      key: 'commissionAmount',
      width: 120,
      render: (amount: number) => (
        <span style={{ color: '#52c41a', fontWeight: 600 }}>
          ¥{formatMoney(amount)}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap: Record<string, { text: string; color: string }> = {
          pending: { text: '待结算', color: 'orange' },
          settled: { text: '已结算', color: 'green' },
          frozen: { text: '已冻结', color: 'red' },
        };
        const config = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '结算时间',
      dataIndex: 'settledAt',
      key: 'settledAt',
      width: 160,
      render: (time: string) => time ? formatDateTime(time) : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (time: string) => formatDateTime(time),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }} title="佣金统计">
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="今日佣金"
              value={statistics.todayCommission}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="本月佣金"
              value={statistics.monthCommission}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="累计佣金"
              value={statistics.totalCommission}
              prefix="¥"
              precision={2}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="待结算佣金"
              value={statistics.pendingCommission}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#faad14' }}
            />
          </Col>
        </Row>
      </Card>

      <Card
        title="佣金明细"
        extra={
          <Space>
            <RangePicker value={dateRange} onChange={handleDateChange} />
            <Button onClick={handleSearch}>查询</Button>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          onChange={handleTableChange}
          summary={(pageData) => {
            if (pageData.length === 0) return null;

            const totalOrderAmount = pageData.reduce((sum, record) => sum + record.orderAmount, 0);
            const totalCommission = pageData.reduce((sum, record) => sum + record.commissionAmount, 0);

            return (
              <Table.Summary fixed>
                <Table.Summary.Row style={{ fontWeight: 600 }}>
                  <Table.Summary.Cell index={0} colSpan={3}>合计</Table.Summary.Cell>
                  <Table.Summary.Cell index={3}>¥{formatMoney(totalOrderAmount)}</Table.Summary.Cell>
                  <Table.Summary.Cell index={4}>-</Table.Summary.Cell>
                  <Table.Summary.Cell index={5}>
                    <span style={{ color: '#52c41a' }}>¥{formatMoney(totalCommission)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={6} colSpan={3}>-</Table.Summary.Cell>
                </Table.Summary.Row>
              </Table.Summary>
            );
          }}
        />
      </Card>
    </div>
  );
};

export default ServiceFees;
