import React, { useEffect, useState } from 'react';
import { Card, Table, Tabs, Form, Input, Button, Space, Tag } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { getPlatformAccounts, getUserAccounts, getMerchantAccounts } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';

const { TabPane } = Tabs;

interface Account {
  id: number;
  userId?: number;
  merchantId?: number;
  userName?: string;
  merchantName?: string;
  balance: number;
  frozenAmount: number;
  availableAmount: number;
  totalIncome: number;
  totalExpense: number;
  status: string;
  createdAt: string;
}

const Accounts: React.FC = () => {
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState('platform');
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });

  useEffect(() => {
    fetchAccounts();
  }, [activeTab]);

  const fetchAccounts = async (params: any = {}) => {
    setLoading(true);
    try {
      const values = form.getFieldsValue();
      const queryParams = {
        ...values,
        ...params,
        page: params.page || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
      };

      let res;
      if (activeTab === 'platform') {
        res = await getPlatformAccounts(queryParams);
      } else if (activeTab === 'user') {
        res = await getUserAccounts(queryParams);
      } else {
        res = await getMerchantAccounts(queryParams);
      }

      setAccounts(res.data.items);
      setPagination({ ...pagination, total: res.data.total, ...params });
    } catch (error) {
      console.error('获取账户列表失败', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    fetchAccounts({ page: 1 });
  };

  const handleReset = () => {
    form.resetFields();
    fetchAccounts({ page: 1 });
  };

  const platformColumns: ColumnsType<Account> = [
    {
      title: '账户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '账户余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => `¥${balance.toFixed(2)}`,
    },
    {
      title: '冻结金额',
      dataIndex: 'frozenAmount',
      key: 'frozenAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '可用余额',
      dataIndex: 'availableAmount',
      key: 'availableAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '累计收入',
      dataIndex: 'totalIncome',
      key: 'totalIncome',
      width: 120,
      render: (amount: number) => <span style={{ color: '#52c41a' }}>¥{amount.toFixed(2)}</span>,
    },
    {
      title: '累计支出',
      dataIndex: 'totalExpense',
      key: 'totalExpense',
      width: 120,
      render: (amount: number) => <span style={{ color: '#ff4d4f' }}>¥{amount.toFixed(2)}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '冻结'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
  ];

  const userColumns: ColumnsType<Account> = [
    {
      title: '账户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      width: 150,
    },
    {
      title: '账户余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => `¥${balance.toFixed(2)}`,
    },
    {
      title: '冻结金额',
      dataIndex: 'frozenAmount',
      key: 'frozenAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '可用余额',
      dataIndex: 'availableAmount',
      key: 'availableAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '冻结'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
  ];

  const merchantColumns: ColumnsType<Account> = [
    {
      title: '账户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '商家ID',
      dataIndex: 'merchantId',
      key: 'merchantId',
      width: 100,
    },
    {
      title: '商家名称',
      dataIndex: 'merchantName',
      key: 'merchantName',
      width: 200,
    },
    {
      title: '账户余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => `¥${balance.toFixed(2)}`,
    },
    {
      title: '冻结金额',
      dataIndex: 'frozenAmount',
      key: 'frozenAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '可用余额',
      dataIndex: 'availableAmount',
      key: 'availableAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '冻结'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
  ];

  const getColumns = () => {
    if (activeTab === 'platform') return platformColumns;
    if (activeTab === 'user') return userColumns;
    return merchantColumns;
  };

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>账户管理</h2>

      <Card>
        <Tabs activeKey={activeTab} onChange={(key) => { setActiveTab(key); setPagination({ current: 1, pageSize: 20, total: 0 }); }}>
          <TabPane tab="平台账户" key="platform" />
          <TabPane tab="用户账户" key="user" />
          <TabPane tab="商家账户" key="merchant" />
        </Tabs>

        {activeTab !== 'platform' && (
          <div style={{ marginBottom: 16 }}>
            <Form form={form} layout="inline">
              {activeTab === 'user' && (
                <>
                  <Form.Item name="userId" label="用户ID">
                    <Input placeholder="请输入用户ID" style={{ width: 150 }} />
                  </Form.Item>
                  <Form.Item name="userName" label="用户名">
                    <Input placeholder="请输入用户名" style={{ width: 150 }} />
                  </Form.Item>
                </>
              )}
              {activeTab === 'merchant' && (
                <>
                  <Form.Item name="merchantId" label="商家ID">
                    <Input placeholder="请输入商家ID" style={{ width: 150 }} />
                  </Form.Item>
                  <Form.Item name="merchantName" label="商家名称">
                    <Input placeholder="请输入商家名称" style={{ width: 150 }} />
                  </Form.Item>
                </>
              )}
              <Form.Item>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                    查询
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={handleReset}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        )}

        <Table
          columns={getColumns()}
          dataSource={accounts}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => fetchAccounts({ page, pageSize }),
          }}
        />
      </Card>
    </div>
  );
};

export default Accounts;
