import React, { useEffect, useState } from 'react';
import { Table, Tag, Button, Space, Select, Input, Popconfirm, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getUserList, freezeUser, unfreezeUser } from '@/api/admin';

const { Option } = Select;
const { Search } = Input;

const statusMap: Record<string, { color: string; label: string }> = {
  active: { color: 'green', label: '正常' },
  frozen: { color: 'red', label: '已冻结' },
  deleted: { color: 'default', label: '已注销' },
};

const UserList: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [keyword, setKeyword] = useState('');
  const [role, setRole] = useState<string>('');
  const [loading, setLoading] = useState(false);

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

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

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

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

  const handleSearch = (value: string) => {
    setKeyword(value);
    setPage(1);
    fetchData();
  };

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '昵称', dataIndex: 'nickname', width: 120, ellipsis: true },
    { title: '手机号', dataIndex: 'phone', width: 130 },
    {
      title: '角色', dataIndex: 'role', width: 100,
      render: (r) => <Tag color={r === 'admin' ? 'blue' : r === 'merchant' ? 'orange' : 'default'}>{r === 'admin' ? '管理员' : r === 'merchant' ? '商家' : '用户'}</Tag>,
    },
    {
      title: '状态', dataIndex: 'status', width: 100,
      render: (s) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.label || s}</Tag>,
    },
    { title: '注册时间', dataIndex: 'createdAt', width: 180 },
    {
      title: '操作', width: 150, fixed: 'right',
      render: (_, r) => (
        <Space size="small">
          {r.status === 'active' && (
            <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>
        <Space>
          <Search placeholder="搜索手机号/昵称" allowClear onSearch={handleSearch} style={{ width: 220 }} />
          <Select value={role || undefined} placeholder="角色" style={{ width: 120 }} allowClear onChange={(v) => { setRole(v || ''); setPage(1); }}>
            <Option value="user">用户</Option>
            <Option value="merchant">商家</Option>
            <Option value="admin">管理员</Option>
          </Select>
        </Space>
      </div>
      <Table rowKey="id" columns={columns} dataSource={data} loading={loading} scroll={{ x: 900 }} pagination={{ current: page, total, pageSize: 10, onChange: setPage }} />
    </div>
  );
};

export default UserList;
