import React, { useEffect, useState } from 'react';
import { Card, Table, Statistic, Row, Col, Space, Tag } from 'antd';
import { ClockCircleOutlined, DollarOutlined, FileTextOutlined, CalendarOutlined } from '@ant-design/icons';
import { getPendingSettlementOrders, getPendingSettlementSummary } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import { formatMoney, formatDate, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';

interface PendingOrder {
  id: number;
  orderNo: string;
  roomName: string;
  checkInDate: string;
  checkOutDate: string;
  nights: number;
  payAmount: number;
  serviceFee: number;
  merchantIncome: number;
  checkoutAt: string;
  contactName: string;
  contactPhone: string;
}

interface Summary {
  orderCount: number;
  totalPayAmount: number;
  totalServiceFee: number;
  totalMerchantIncome: number;
  startDate: string;
  lastSettlementDate: string | null;
}

const PendingSettlement: React.FC = () => {
  const [summary, setSummary] = useState<Summary | null>(null);
  const [summaryLoading, setSummaryLoading] = useState(false);

  const {
    data: orders,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    refresh,
  } = useTableData<PendingOrder>({
    fetchFn: async (params) => {
      const res = await getPendingSettlementOrders(params);
      return {
        list: res.data.list || [],
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 20)),
      };
    },
    initialParams: { pageSize: 20 },
  });

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

  const fetchSummary = async () => {
    setSummaryLoading(true);
    try {
      const res = await getPendingSettlementSummary();
      setSummary(res.data);
    } catch (error) {
      console.error('获取待结算统计失败', error);
    } finally {
      setSummaryLoading(false);
    }
  };

  const columns: ColumnsType<PendingOrder> = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
      fixed: 'left',
    },
    {
      title: '房型名称',
      dataIndex: 'roomName',
      key: 'roomName',
      width: 150,
    },
    {
      title: '入住日期',
      dataIndex: 'checkInDate',
      key: 'checkInDate',
      width: 120,
      render: (date: string) => formatDate(date),
    },
    {
      title: '离店日期',
      dataIndex: 'checkOutDate',
      key: 'checkOutDate',
      width: 120,
      render: (date: string) => formatDate(date),
    },
    {
      title: '入住晚数',
      dataIndex: 'nights',
      key: 'nights',
      width: 100,
      render: (nights: number) => `${nights}晚`,
    },
    {
      title: '订单金额',
      dataIndex: 'payAmount',
      key: 'payAmount',
      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: 'merchantIncome',
      key: 'merchantIncome',
      width: 120,
      render: (income: number) => (
        <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{formatMoney(income)}</span>
      ),
    },
    {
      title: '完成时间',
      dataIndex: 'checkoutAt',
      key: 'checkoutAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '联系人',
      key: 'contact',
      width: 150,
      render: (_, record) => (
        <div>
          <div>{record.contactName}</div>
          <div style={{ fontSize: 12, color: '#999' }}>{record.contactPhone}</div>
        </div>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>待结算订单</h2>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card loading={summaryLoading}>
            <Statistic
              title="待结算订单数"
              value={summary?.orderCount || 0}
              prefix={<FileTextOutlined />}
              suffix="笔"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card loading={summaryLoading}>
            <Statistic
              title="订单总金额"
              value={summary?.totalPayAmount || 0}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="元"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card loading={summaryLoading}>
            <Statistic
              title="平台服务费"
              value={summary?.totalServiceFee || 0}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card loading={summaryLoading}>
            <Statistic
              title="预计结算金额"
              value={summary?.totalMerchantIncome || 0}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Card
        extra={
          <Space>
            {summary?.lastSettlementDate && (
              <Tag icon={<CalendarOutlined />} color="blue">
                上次结算: {formatDate(summary.lastSettlementDate)}
              </Tag>
            )}
            <Tag icon={<ClockCircleOutlined />} color="orange">
              统计起始: {summary?.startDate ? formatDate(summary.startDate) : '-'}
            </Tag>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>
    </div>
  );
};

export default PendingSettlement;
