import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Tag, Button, Table, message, Spin } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getSettlementDetail, getSettlementItems } from '@/api/finance';

const statusMap: Record<string, { color: string; label: string }> = {
  pending: { color: 'gold', label: '待结算' },
  completed: { color: 'green', label: '已结算' },
};

const SettlementDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [settlement, setSettlement] = useState<any>(null);
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [itemsLoading, setItemsLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const fetchDetail = async () => {
    setLoading(true);
    try {
      const res: any = await getSettlementDetail(Number(id));
      setSettlement(res.data);
    } catch (error) {
      message.error('加载结算详情失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchItems = async () => {
    setItemsLoading(true);
    try {
      const res: any = await getSettlementItems(Number(id), { page, pageSize: 10 });
      setItems(res.data?.list || []);
      setTotal(res.data?.total || 0);
    } catch (error) {
      message.error('加载结算明细失败');
    } finally {
      setItemsLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchDetail();
      fetchItems();
    }
  }, [id, page]);

  const columns: ColumnsType<any> = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      width: 200,
    },
    {
      title: '房源名称',
      dataIndex: 'roomTitle',
      width: 150,
      ellipsis: true,
    },
    {
      title: '入住日期',
      dataIndex: 'checkInDate',
      width: 120,
    },
    {
      title: '离店日期',
      dataIndex: 'checkOutDate',
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      width: 120,
      render: (value) => `¥${Number(value).toFixed(2)}`,
    },
    {
      title: '服务费',
      dataIndex: 'serviceFee',
      width: 120,
      render: (value) => <span style={{ color: '#ff4d4f' }}>-¥{Number(value).toFixed(2)}</span>,
    },
    {
      title: '结算金额',
      dataIndex: 'settlementAmount',
      width: 120,
      render: (value) => <span style={{ color: '#52c41a', fontWeight: 600 }}>¥{Number(value).toFixed(2)}</span>,
    },
    {
      title: '完成时间',
      dataIndex: 'completedAt',
      width: 180,
    },
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!settlement) {
    return <div>结算单不存在</div>;
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>
          返回
        </Button>
      </div>

      <Card title="结算单信息" style={{ marginBottom: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="结算周期">
            {settlement.startDate} 至 {settlement.endDate}
          </Descriptions.Item>
          <Descriptions.Item label="结算状态">
            <Tag color={statusMap[settlement.status]?.color}>
              {statusMap[settlement.status]?.label || settlement.status}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="订单数量">{settlement.orderCount} 笔</Descriptions.Item>
          <Descriptions.Item label="订单总额">¥{Number(settlement.totalAmount).toFixed(2)}</Descriptions.Item>
          <Descriptions.Item label="服务费率">{settlement.serviceFeeRate}%</Descriptions.Item>
          <Descriptions.Item label="服务费">
            <span style={{ color: '#ff4d4f' }}>-¥{Number(settlement.serviceFee).toFixed(2)}</span>
          </Descriptions.Item>
          <Descriptions.Item label="结算金额" span={2}>
            <span style={{ fontSize: 20, fontWeight: 600, color: '#52c41a' }}>
              ¥{Number(settlement.settlementAmount).toFixed(2)}
            </span>
          </Descriptions.Item>
          {settlement.settledAt && (
            <Descriptions.Item label="结算时间" span={2}>
              {settlement.settledAt}
            </Descriptions.Item>
          )}
          <Descriptions.Item label="创建时间" span={2}>
            {settlement.createdAt}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      <Card title={`订单明细（共 ${total} 笔）`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={items}
          loading={itemsLoading}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            total,
            pageSize: 10,
            onChange: setPage,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />

        <div style={{ marginTop: 16, padding: 16, background: '#fafafa', borderRadius: 4 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span>订单总额：</span>
            <span style={{ fontWeight: 600 }}>¥{Number(settlement.totalAmount).toFixed(2)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span>服务费（{settlement.serviceFeeRate}%）：</span>
            <span style={{ fontWeight: 600, color: '#ff4d4f' }}>-¥{Number(settlement.serviceFee).toFixed(2)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 8, borderTop: '1px solid #d9d9d9' }}>
            <span style={{ fontSize: 16, fontWeight: 600 }}>结算金额：</span>
            <span style={{ fontSize: 20, fontWeight: 600, color: '#52c41a' }}>
              ¥{Number(settlement.settlementAmount).toFixed(2)}
            </span>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default SettlementDetail;
