import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Tag, Popconfirm, message, Select } from 'antd';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { getMerchantRooms, removeRoom, updateRoom } from '@/api/room';

const typeLabels: Record<string, string> = { hotel: '酒店', homestay: '民宿', apartment: '公寓', hostel: '青旅' };
const auditStatusMap: Record<string, { label: string; color: string }> = {
  pending: { label: '审核中', color: 'orange' },
  approved: { label: '已通过', color: 'green' },
  rejected: { label: '已拒绝', color: 'red' },
};

const RoomList: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState<string | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

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

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

  const handleRemove = async (id: number) => {
    await removeRoom(id);
    message.success('已下架');
    fetchData();
  };

  const handleRelist = async (id: number) => {
    await updateRoom(id, { status: 'on_sale' });
    message.success('已上架');
    fetchData();
  };

  const columns: ColumnsType<any> = [
    {
      title: '封面', dataIndex: 'coverImage', width: 100,
      render: (url) => url ? <img src={url} style={{ width: 80, height: 60, objectFit: 'cover', borderRadius: 4 }} /> : '-',
    },
    { title: '名称', dataIndex: 'name', width: 180, ellipsis: true },
    { title: '类型', dataIndex: 'type', width: 80, render: (t) => typeLabels[t] || t },
    { title: '价格/晚', dataIndex: 'price', width: 100, render: (v) => `¥${v}` },
    { title: '评分', dataIndex: 'rating', width: 80 },
    { title: '评价数', dataIndex: 'reviewCount', width: 80 },
    {
      title: '状态', dataIndex: 'status', width: 100,
      render: (s) => <Tag color={s === 'on_sale' ? 'green' : 'default'}>{s === 'on_sale' ? '在售' : '已下架'}</Tag>,
    },
    {
      title: '审核状态', dataIndex: 'auditStatus', width: 100,
      render: (s) => {
        const info = auditStatusMap[s] || { label: s, color: 'default' };
        return <Tag color={info.color}>{info.label}</Tag>;
      },
    },
    {
      title: '操作', width: 240, fixed: 'right',
      render: (_, r) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => navigate(`/rooms/edit/${r.id}`)}>编辑</Button>
          <Button type="link" size="small" onClick={() => navigate(`/room-calendar/${r.id}`)}>日历</Button>
          {r.auditStatus !== 'pending' && (
            r.status === 'on_sale' ? (
              <Popconfirm title="确定下架？" onConfirm={() => handleRemove(r.id)}>
                <Button type="link" danger size="small">下架</Button>
              </Popconfirm>
            ) : (
              <Popconfirm title="确定上架？" onConfirm={() => handleRelist(r.id)}>
                <Button type="link" size="small">上架</Button>
              </Popconfirm>
            )
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Space>
          <h2 style={{ margin: 0 }}>房源管理</h2>
          <Select
            placeholder="状态筛选"
            allowClear
            style={{ width: 120 }}
            value={status}
            onChange={(v) => { setStatus(v); setPage(1); }}
            options={[
              { label: '在售', value: 'on_sale' },
              { label: '已下架', value: 'off_sale' },
            ]}
          />
        </Space>
        <Button type="primary" onClick={() => navigate('/rooms/create')}>添加房源</Button>
      </div>
      <Table rowKey="id" columns={columns} dataSource={data} loading={loading} scroll={{ x: 1000 }} pagination={{ current: page, total, pageSize: 10, onChange: setPage }} />
    </div>
  );
};

export default RoomList;
