import React, { useState } from 'react';
import { Card, Table, Button, Space, Modal, Descriptions, message } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import { getMerchantSettlements, getSettlementDetail, getSettlementItems } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import type { Settlement } from '@rent/shared-types';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';
import { SettlementStatusTag } from '@/components/SettlementStatusTag';

interface SettlementItem {
  id: number;
  orderId: number;
  orderNo: string;
  orderAmount: number;
  serviceFee: number;
  settlementAmount: number;
}

const Settlements: React.FC = () => {
  const {
    data: settlements,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
  } = useTableData<Settlement>({
    fetchFn: async (params) => {
      const res = await getMerchantSettlements(params);
      return {
        list: res.data.list || res.data.items || [],
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 20)),
      };
    },
    initialParams: { pageSize: 20 },
  });

  const detailModal = useModal<Settlement>();
  const itemsModal = useModal<number>();
  const [items, setItems] = useState<SettlementItem[]>([]);
  const [itemsLoading, setItemsLoading] = useState(false);
  const [itemsPagination, setItemsPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  const handleViewDetail = async (settlement: Settlement) => {
    detailModal.open(settlement);
  };

  const handleViewItems = async (id: number, page = 1, pageSize = 10) => {
    setItemsLoading(true);
    try {
      const res = await getSettlementItems(id, { page, pageSize });
      setItems(res.data.items);
      setItemsPagination({ current: page, pageSize, total: res.data.total });
      itemsModal.open(id);
    } catch (error) {
      message.error('获取结算明细失败');
    } finally {
      setItemsLoading(false);
    }
  };

  const columns: ColumnsType<Settlement> = [
    {
      title: '结算ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '结算周期',
      key: 'period',
      width: 200,
      render: (_, record) => `${record.periodStart} ~ ${record.periodEnd}`,
    },
    {
      title: '订单数',
      dataIndex: 'orderCount',
      key: 'orderCount',
      width: 100,
    },
    {
      title: '订单总额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '平台服务费',
      dataIndex: 'serviceFee',
      key: 'serviceFee',
      width: 120,
      render: (fee: number) => <span style={{ color: '#ff4d4f' }}>-{formatMoney(fee, '')}</span>,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementAmount',
      key: 'settlementAmount',
      width: 120,
      render: (amount: number) => (
        <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{formatMoney(amount)}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => <SettlementStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: Settlement) => (
        <Space>
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            详情
          </Button>
          <Button type="link" size="small" onClick={() => handleViewItems(record.id)}>
            明细
          </Button>
        </Space>
      ),
    },
  ];

  const itemColumns: ColumnsType<SettlementItem> = [
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 100,
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '服务费',
      dataIndex: 'serviceFee',
      key: 'serviceFee',
      width: 120,
      render: (fee: number) => <span style={{ color: '#ff4d4f' }}>{formatMoney(fee)}</span>,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementAmount',
      key: 'settlementAmount',
      width: 120,
      render: (amount: number) => <span style={{ color: '#52c41a' }}>{formatMoney(amount)}</span>,
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>结算记录</h2>

      <Card>
        <Table
          columns={columns}
          dataSource={settlements}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      <Modal
        title="结算详情"
        open={detailModal.visible}
        onCancel={detailModal.close}
        footer={null}
        width={600}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="结算ID">{detailModal.data.id}</Descriptions.Item>
            <Descriptions.Item label="结算周期">
              {detailModal.data.periodStart} ~ {detailModal.data.periodEnd}
            </Descriptions.Item>
            <Descriptions.Item label="订单数量">{detailModal.data.orderCount} 笔</Descriptions.Item>
            <Descriptions.Item label="订单总额">{formatMoney(detailModal.data.orderAmount)}</Descriptions.Item>
            <Descriptions.Item label="平台服务费">
              <span style={{ color: '#ff4d4f' }}>{formatMoney(detailModal.data.serviceFee)}</span>
            </Descriptions.Item>
            <Descriptions.Item label="结算金额">
              <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
                {formatMoney(detailModal.data.settlementAmount)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <SettlementStatusTag status={detailModal.data.status} />
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{formatDateTime(detailModal.data.createdAt)}</Descriptions.Item>
            {detailModal.data.settledAt && (
              <Descriptions.Item label="结算时间">{formatDateTime(detailModal.data.settledAt)}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      <Modal
        title="结算明细"
        open={itemsModal.visible}
        onCancel={itemsModal.close}
        footer={null}
        width={900}
      >
        <Table
          columns={itemColumns}
          dataSource={items}
          rowKey="id"
          loading={itemsLoading}
          pagination={{
            ...itemsPagination,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              if (itemsModal.data) {
                handleViewItems(itemsModal.data, page, pageSize);
              }
            },
          }}
        />
      </Modal>
    </div>
  );
};

export default Settlements;
