import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Tag, Button, Space, Tabs, Table, Statistic, Row, Col, message, Popconfirm, Modal, Input, Spin } from 'antd';
import { ArrowLeftOutlined, ShopOutlined, PhoneOutlined, EnvironmentOutlined, StarOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getMerchantDetail, approveMerchant, rejectMerchant, freezeMerchant, unfreezeMerchant } from '@/api/admin';

const statusMap: Record<string, { color: string; label: string }> = {
  pending: { color: 'gold', label: '待审核' },
  approved: { color: 'green', label: '已通过' },
  rejected: { color: 'red', label: '已拒绝' },
  frozen: { color: 'default', label: '已冻结' },
};

const MerchantDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [merchant, setMerchant] = useState<any>(null);
  const [rejectModal, setRejectModal] = useState<{ visible: boolean; reason: string }>({ visible: false, reason: '' });

  const fetchData = async () => {
    if (!id) return;
    setLoading(true);
    try {
      const res: any = await getMerchantDetail(Number(id));
      setMerchant(res.data);
    } catch (error) {
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

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

  const handleApprove = async () => {
    await approveMerchant(Number(id));
    message.success('已通过审核');
    fetchData();
  };

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

  const handleFreeze = async () => {
    await freezeMerchant(Number(id));
    message.success('已冻结');
    fetchData();
  };

  const handleUnfreeze = async () => {
    await unfreezeMerchant(Number(id));
    message.success('已解冻');
    fetchData();
  };

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

  const roomColumns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '房源名称', dataIndex: 'title', ellipsis: true },
    { title: '价格', dataIndex: 'price', width: 100, render: (v) => `¥${v}` },
    { title: '面积', dataIndex: 'area', width: 100, render: (v) => `${v}㎡` },
    { title: '状态', dataIndex: 'status', width: 100, render: (s) => <Tag color={s === 'available' ? 'green' : 'default'}>{s === 'available' ? '可租' : '已租'}</Tag> },
    { title: '发布时间', dataIndex: 'createdAt', width: 180 },
  ];

  const orderColumns: ColumnsType<any> = [
    { title: '订单号', dataIndex: 'orderNo', width: 180 },
    { title: '房源', dataIndex: 'roomTitle', ellipsis: true },
    { title: '租客', dataIndex: 'userName', width: 120 },
    { title: '金额', dataIndex: 'totalAmount', width: 100, render: (v) => `¥${v}` },
    { title: '状态', dataIndex: 'status', width: 120, render: (s) => <Tag>{s}</Tag> },
    { title: '下单时间', dataIndex: 'createdAt', width: 180 },
  ];

  const reviewColumns: ColumnsType<any> = [
    { title: '订单号', dataIndex: 'orderNo', width: 180 },
    { title: '评价人', dataIndex: 'userName', width: 120 },
    { title: '评分', dataIndex: 'rating', width: 100, render: (v) => <><StarOutlined style={{ color: '#faad14' }} /> {v}</> },
    { title: '评价内容', dataIndex: 'content', ellipsis: true },
    { title: '评价时间', dataIndex: 'createdAt', width: 180 },
  ];

  return (
    <div>
      {/* 头部 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>返回</Button>
          <h2 style={{ margin: 0 }}>商家详情</h2>
        </Space>
        <Space>
          {merchant.status === 'pending' && (
            <>
              <Button type="primary" onClick={handleApprove}>通过审核</Button>
              <Button danger onClick={() => setRejectModal({ visible: true, reason: '' })}>拒绝</Button>
            </>
          )}
          {merchant.status === 'approved' && (
            <Popconfirm title="确定冻结该商家？" onConfirm={handleFreeze}>
              <Button danger>冻结</Button>
            </Popconfirm>
          )}
          {merchant.status === 'frozen' && (
            <Button type="primary" onClick={handleUnfreeze}>解冻</Button>
          )}
        </Space>
      </div>

      {/* 基本信息 */}
      <Card title={<><ShopOutlined /> 基本信息</>} style={{ marginBottom: 16 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="商家ID">{merchant.id}</Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={statusMap[merchant.status]?.color}>{statusMap[merchant.status]?.label}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="店铺名称">{merchant.shopName}</Descriptions.Item>
          <Descriptions.Item label="联系电话">
            <PhoneOutlined /> {merchant.phone}
          </Descriptions.Item>
          <Descriptions.Item label="所在城市">
            <EnvironmentOutlined /> {merchant.city}
          </Descriptions.Item>
          <Descriptions.Item label="详细地址">{merchant.address || '-'}</Descriptions.Item>
          <Descriptions.Item label="营业时间">{merchant.businessHours || '-'}</Descriptions.Item>
          <Descriptions.Item label="店铺简介" span={2}>{merchant.description || '-'}</Descriptions.Item>
          <Descriptions.Item label="入驻时间">{merchant.createdAt}</Descriptions.Item>
          <Descriptions.Item label="更新时间">{merchant.updatedAt}</Descriptions.Item>
          {merchant.status === 'rejected' && (
            <Descriptions.Item label="拒绝原因" span={2}>
              <span style={{ color: '#ff4d4f' }}>{merchant.rejectReason}</span>
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      {/* 统计数据 */}
      <Card title="经营数据" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic title="房源数量" value={merchant.stats?.roomCount || 0} suffix="个" />
          </Col>
          <Col span={6}>
            <Statistic title="订单数量" value={merchant.stats?.orderCount || 0} suffix="单" />
          </Col>
          <Col span={6}>
            <Statistic title="累计收入" value={merchant.stats?.totalIncome || 0} prefix="¥" precision={2} />
          </Col>
          <Col span={6}>
            <Statistic
              title="店铺评分"
              value={merchant.rating || 0}
              precision={1}
              suffix={<span style={{ fontSize: 14, color: '#999' }}>/ 5.0 ({merchant.reviewCount || 0}条评价)</span>}
            />
          </Col>
        </Row>
      </Card>

      {/* 详细信息标签页 */}
      <Card>
        <Tabs
          items={[
            {
              key: 'rooms',
              label: `房源列表 (${merchant.rooms?.length || 0})`,
              children: (
                <Table
                  rowKey="id"
                  columns={roomColumns}
                  dataSource={merchant.rooms || []}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
            {
              key: 'orders',
              label: `订单列表 (${merchant.orders?.length || 0})`,
              children: (
                <Table
                  rowKey="id"
                  columns={orderColumns}
                  dataSource={merchant.orders || []}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
            {
              key: 'reviews',
              label: `评价列表 (${merchant.reviews?.length || 0})`,
              children: (
                <Table
                  rowKey="id"
                  columns={reviewColumns}
                  dataSource={merchant.reviews || []}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
          ]}
        />
      </Card>

      {/* 拒绝弹窗 */}
      <Modal
        title="拒绝商家入驻"
        open={rejectModal.visible}
        onOk={handleReject}
        onCancel={() => setRejectModal({ visible: false, reason: '' })}
      >
        <Input.TextArea
          rows={3}
          placeholder="请输入拒绝原因"
          value={rejectModal.reason}
          onChange={(e) => setRejectModal({ ...rejectModal, reason: e.target.value })}
        />
      </Modal>
    </div>
  );
};

export default MerchantDetail;
