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;
  user_id?: number;
  merchant_id?: number;
  userName?: string;
  merchantName?: string;
  account_name?: string;
  balance: number | string;
  frozen_balance: number | string;
  total_income: number | string;
  total_expense: number | string;
  status: string;
  created_at: string;
  updated_at: 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);
      }

      // 后端返回的是数组，不是分页对象
      const data = Array.isArray(res.data) ? res.data : (res.data.items || res.data.list || []);
      setAccounts(data);
      setPagination({ ...pagination, total: data.length, ...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: 'account_name',
      key: 'account_name',
      width: 150,
    },
    {
      title: '账户余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number | string) => `¥${Number(balance).toFixed(2)}`,
    },
    {
      title: '冻结金额',
      dataIndex: 'frozen_balance',
      key: 'frozen_balance',
      width: 120,
      render: (amount: number | string) => `¥${Number(amount).toFixed(2)}`,
    },
    {
      title: '可用余额',
      key: 'availableAmount',
      width: 120,
      render: (record: Account) => {
        const available = Number(record.balance) - Number(record.frozen_balance);
        return `¥${available.toFixed(2)}`;
      },
    },
    {
      title: '累计收入',
      dataIndex: 'total_income',
      key: 'total_income',
      width: 120,
      render: (amount: number | string) => <span style={{ color: '#52c41a' }}>¥{Number(amount).toFixed(2)}</span>,
    },
    {
      title: '累计支出',
      dataIndex: 'total_expense',
      key: 'total_expense',
      width: 120,
      render: (amount: number | string) => <span style={{ color: '#ff4d4f' }}>¥{Number(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: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
  ];

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

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

  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;
