import React, { useEffect, useState } from 'react';
import { Table, Tag, Button, Space, Modal, Input, Select, message, Popconfirm } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getMerchantOrders, confirmOrder, rejectOrder, checkinOrder, checkoutOrder, exportOrders } from '@/api/order';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;

const statusMap: Record<string, { color: string; label: string }> = {
  pending_pay: { color: 'gold', label: '待支付' },
  pending_confirm: { color: 'blue', label: '待确认' },
  pending_checkin: { color: 'cyan', label: '待入住' },
  checked_in: { color: 'orange', label: '已入住' },
  completed: { color: 'green', label: '已完成' },
  cancelled: { color: 'default', label: '已取消' },
  refunding: { color: 'red', label: '退款中' },
  refunded: { color: 'purple', label: '已退款' },
};

const OrderList: React.FC = () => {
  const navigate = useNavigate();
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [rejectModal, setRejectModal] = useState<{ visible: boolean; orderNo: string | null; reason: string }>({ visible: false, orderNo: null, reason: '' });

  const fetchData = async () => {
    setLoading(true);
    try {
      const res: any = await getMerchantOrders({ page, pageSize: 10, status: status || undefined });
      setData(res.data?.list || []);
      setTotal(res.data?.total || 0);
    } finally {
      setLoading(false);
    }
  };

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

  const handleConfirm = async (orderNo: string) => {
    await confirmOrder(orderNo);
    message.success('已确认');
    fetchData();
  };

  const handleCheckin = async (orderNo: string) => {
    await checkinOrder(orderNo);
    message.success('已办理入住');
    fetchData();
  };

  const handleCheckout = async (orderNo: string) => {
    await checkoutOrder(orderNo);
    message.success('已确认离店');
    fetchData();
  };

  const handleReject = async () => {
    if (!rejectModal.reason) { message.warning('请填写拒绝原因'); return; }
    await rejectOrder(rejectModal.orderNo!, rejectModal.reason);
    message.success('已拒绝');
    setRejectModal({ visible: false, orderNo: null, reason: '' });
    fetchData();
  };

  const handleExport = async () => {
    setExporting(true);
    try {
      const res: any = await exportOrders({ status: status || undefined });
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `订单列表_${new Date().toISOString().split('T')[0]}.xlsx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    } finally {
      setExporting(false);
    }
  };

  // 判断是否可以确认离店
  const canCheckout = (record: any) => {
    if (record.status !== 'checked_in') return false;
    const today = new Date().toISOString().split('T')[0];
    return record.checkOutDate <= today;
  };

  const columns: ColumnsType<any> = [
    { title: '订单号', dataIndex: 'orderNo', width: 200 },
    { title: '房源', dataIndex: ['room', 'name'], width: 150, ellipsis: true },
    { title: '入住日期', dataIndex: 'checkInDate', width: 120 },
    { title: '离店日期', dataIndex: 'checkOutDate', width: 120 },
    { title: '金额', dataIndex: 'payAmount', width: 100, render: (v) => `¥${v}` },
    {
      title: '状态', dataIndex: 'status', width: 100,
      render: (s) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.label || s}</Tag>,
    },
    { title: '联系人', dataIndex: 'contactName', width: 100 },
    { title: '手机号', dataIndex: 'contactPhone', width: 130 },
    {
      title: '操作', width: 250, fixed: 'right',
      render: (_, r) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => navigate(`/orders/${r.orderNo}`)}>详情</Button>
          {r.status === 'pending_confirm' && (
            <>
              <Button type="primary" size="small" onClick={() => handleConfirm(r.orderNo)}>确认</Button>
              <Button danger size="small" onClick={() => setRejectModal({ visible: true, orderNo: r.orderNo, reason: '' })}>拒绝</Button>
            </>
          )}
          {r.status === 'pending_checkin' && (
            <Button type="primary" size="small" onClick={() => handleCheckin(r.orderNo)}>办理入住</Button>
          )}
          {canCheckout(r) && (
            <Popconfirm title="确认客人已离店？订单将标记为已完成" onConfirm={() => handleCheckout(r.orderNo)} okText="确认" cancelText="取消">
              <Button type="primary" size="small">确认离店</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h2>订单管理</h2>
        <Space>
          <Select value={status || undefined} placeholder="订单状态" style={{ width: 150 }} allowClear onChange={(v) => { setStatus(v || ''); setPage(1); }}>
            {Object.entries(statusMap).map(([k, v]) => <Option key={k} value={k}>{v.label}</Option>)}
          </Select>
          <Button icon={<DownloadOutlined />} loading={exporting} onClick={handleExport}>
            导出Excel
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        scroll={{ x: 1400 }}
        pagination={{ current: page, total, pageSize: 10, onChange: setPage }}
      />
      <Modal title="拒绝订单" open={rejectModal.visible} onOk={handleReject} onCancel={() => setRejectModal({ visible: false, orderNo: null, reason: '' })}>
        <Input.TextArea rows={3} placeholder="请输入拒绝原因" value={rejectModal.reason} onChange={(e) => setRejectModal({ ...rejectModal, reason: e.target.value })} />
      </Modal>
    </div>
  );
};

export default OrderList;
