import React, { useEffect, useState } from 'react';
import {
  Button, Card, Form, Input, InputNumber, message, Modal, Popconfirm, Space, Switch, Table, Tag, Typography,
} from 'antd';
import {
  UserOutlined, WalletOutlined, SearchOutlined, StopOutlined, CheckCircleOutlined,
} from '@ant-design/icons';
import { getAdminUsers, adjustCredits, toggleUserStatus } from '../../api';
import type { AdminUser } from '../../types';

const AdminUsers: React.FC = () => {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [creditModal, setCreditModal] = useState<{ open: boolean; user: AdminUser | null }>({ open: false, user: null });
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    const data = await getAdminUsers(search || undefined);
    setUsers(data);
    setLoading(false);
  };

  useEffect(() => { load(); }, []);

  const handleSearch = () => load();

  const handleAdjustCredits = async () => {
    try {
      const values = await form.validateFields();
      const { user } = creditModal;
      if (!user) return;
      await adjustCredits(user.id, values.amount, values.reason);
      message.success(`已${values.amount > 0 ? '增加' : '扣除'} ${Math.abs(values.amount)} 积分`);
      setCreditModal({ open: false, user: null });
      form.resetFields();
      load();
    } catch { /* validation */ }
  };

  const handleToggleStatus = async (user: AdminUser) => {
    await toggleUserStatus(user.id, !user.isActive);
    message.success(user.isActive ? '已禁用该用户' : '已启用该用户');
    load();
  };

  const columns = [
    {
      title: '用户', key: 'user', width: 200,
      render: (_: any, r: AdminUser) => (
        <Space>
          <div style={{
            width: 32, height: 32, borderRadius: 8,
            background: r.isAdmin ? 'linear-gradient(135deg, #f59e0b, #f97316)' : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 13, fontWeight: 700,
          }}>
            {r.username.charAt(0).toUpperCase()}
          </div>
          <div>
            <div style={{ fontWeight: 600 }}>
              {r.username}
              {r.isAdmin && <Tag color="orange" style={{ marginLeft: 6, fontSize: 10 }}>管理员</Tag>}
            </div>
            <div style={{ color: '#94a3b8', fontSize: 12 }}>{r.email}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '积分余额', dataIndex: 'credits', width: 120, sorter: (a: AdminUser, b: AdminUser) => a.credits - b.credits,
      render: (v: number) => (
        <Typography.Text strong style={{ color: v > 0 ? '#10b981' : '#ef4444', fontSize: 15 }}>
          {v.toLocaleString()}
        </Typography.Text>
      ),
    },
    {
      title: '手机号', dataIndex: 'phone', width: 130,
      render: (v: string) => <Typography.Text type="secondary">{v || '-'}</Typography.Text>,
    },
    {
      title: '状态', dataIndex: 'isActive', width: 80,
      render: (v: boolean) => (
        <Tag color={v ? 'green' : 'red'}>{v ? '正常' : '禁用'}</Tag>
      ),
    },
    {
      title: '注册时间', dataIndex: 'createdAt', width: 120,
      render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{v}</Typography.Text>,
    },
    {
      title: '最后登录', dataIndex: 'lastLoginAt', width: 140,
      render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{v || '-'}</Typography.Text>,
    },
    {
      title: '操作', key: 'action', width: 200, fixed: 'right' as const,
      render: (_: any, r: AdminUser) => (
        <Space size={4}>
          <Button type="link" size="small" icon={<WalletOutlined />}
            onClick={() => { setCreditModal({ open: true, user: r }); form.resetFields(); }}>
            调整积分
          </Button>
          {!r.isAdmin && (
            <Popconfirm
              title={r.isActive ? '确定禁用该用户？' : '确定启用该用户？'}
              onConfirm={() => handleToggleStatus(r)}
            >
              <Button type="link" size="small" danger={r.isActive}
                icon={r.isActive ? <StopOutlined /> : <CheckCircleOutlined />}>
                {r.isActive ? '禁用' : '启用'}
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card bordered={false} style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
        {/* Search bar */}
        <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
          <Input
            placeholder="搜索用户名或邮箱"
            prefix={<SearchOutlined style={{ color: '#94a3b8' }} />}
            value={search}
            onChange={e => setSearch(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 280, borderRadius: 8 }}
            allowClear
          />
          <Button type="primary" onClick={handleSearch} style={{ borderRadius: 8 }}>搜索</Button>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10, showTotal: (t) => `共 ${t} 个用户` }}
          scroll={{ x: 900 }}
        />
      </Card>

      {/* Adjust Credits Modal */}
      <Modal
        title={<Space><WalletOutlined />调整积分 - {creditModal.user?.username}</Space>}
        open={creditModal.open}
        onOk={handleAdjustCredits}
        onCancel={() => { setCreditModal({ open: false, user: null }); form.resetFields(); }}
        okText="确认" cancelText="取消" width={440}
      >
        <div style={{ marginBottom: 16, padding: '12px 16px', background: '#f8fafc', borderRadius: 8 }}>
          <span style={{ color: '#64748b' }}>当前积分：</span>
          <span style={{ fontWeight: 800, fontSize: 18, color: '#6366f1' }}>
            {creditModal.user?.credits.toLocaleString()}
          </span>
        </div>
        <Form form={form} layout="vertical">
          <Form.Item name="amount" label="积分变动"
            rules={[{ required: true, message: '请输入积分数量' }]}>
            <InputNumber
              style={{ width: '100%' }}
              size="large"
              placeholder="正数增加，负数扣除"
              formatter={v => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            />
          </Form.Item>
          <Form.Item name="reason" label="原因"
            rules={[{ required: true, message: '请输入调整原因' }]}>
            <Input.TextArea rows={2} placeholder="请输入调整原因" size="large" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminUsers;
