import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Table, Tag, Button, Space, Select, Modal, Input, message, Popconfirm } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getMerchantList, approveMerchant, rejectMerchant, freezeMerchant, unfreezeMerchant } from '@/api/admin';

const { Option } = Select;

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 MerchantList: 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 [rejectModal, setRejectModal] = useState<{ visible: boolean; id: number | null; reason: string }>({ visible: false, id: null, reason: '' });

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

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

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

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

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

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

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      width: 160,
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => navigate(`/merchants/${record.id}`)}>{text}</a>
      ),
    },
    { title: '联系电话', dataIndex: 'phone', width: 130 },
    { title: '城市', dataIndex: 'city', width: 100 },
    { title: '评分', dataIndex: 'rating', width: 80 },
    { title: '评价数', dataIndex: 'reviewCount', width: 80 },
    {
      title: '状态', dataIndex: 'status', width: 100,
      render: (s) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.label || s}</Tag>,
    },
    { title: '入驻时间', dataIndex: 'createdAt', width: 180 },
    {
      title: '操作', width: 300, fixed: 'right',
      render: (_, r) => (
        <Space size="small">
          <Button size="small" onClick={() => navigate(`/merchants/${r.id}`)}>详情</Button>
          {r.status === 'pending' && (
            <>
              <Button type="primary" size="small" onClick={() => handleApprove(r.id)}>通过</Button>
              <Button danger size="small" onClick={() => setRejectModal({ visible: true, id: r.id, reason: '' })}>拒绝</Button>
            </>
          )}
          {r.status === 'approved' && (
            <Popconfirm title="确定冻结该商家？" onConfirm={() => handleFreeze(r.id)}>
              <Button danger size="small">冻结</Button>
            </Popconfirm>
          )}
          {r.status === 'frozen' && (
            <Button type="primary" size="small" onClick={() => handleUnfreeze(r.id)}>解冻</Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h2>商家管理</h2>
        <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>
      </div>
      <Table rowKey="id" columns={columns} dataSource={data} loading={loading} scroll={{ x: 1200 }} pagination={{ current: page, total, pageSize: 10, onChange: setPage }} />
      <Modal title="拒绝商家入驻" open={rejectModal.visible} onOk={handleReject} onCancel={() => setRejectModal({ visible: false, id: null, reason: '' })}>
        <Input.TextArea rows={3} placeholder="请输入拒绝原因" value={rejectModal.reason} onChange={(e) => setRejectModal({ ...rejectModal, reason: e.target.value })} />
      </Modal>
    </div>
  );
};

export default MerchantList;
