import React, { useState } from 'react';
import { Card, Table, Form, Input, Button, Space, DatePicker, Select, Tag, Descriptions, Modal } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons';
import { getPlatformTransactions } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';

const { RangePicker } = DatePicker;

interface PlatformTransaction {
  id: number;
  transaction_no: string;
  account_id: number;
  direction: 'income' | 'expense';
  amount: number;
  balance_before: number;
  balance_after: number;
  transaction_type: string;
  business_type: string;
  business_id: number;
  business_no: string;
  related_account_type?: string;
  related_account_id?: number;
  remark: string;
  created_at: string;
}

const PlatformTransactions: React.FC = () => {
  const [form] = Form.useForm();
  const detailModal = useModal<PlatformTransaction>();

  const {
    data: transactions,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    refresh,
  } = useTableData<PlatformTransaction>({
    fetchFn: async (params) => {
      const res = await getPlatformTransactions(params);
      return {
        list: res.data.items,
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 20)),
      };
    },
    initialParams: { pageSize: 20 },
  });

  const handleSearch = () => {
    const values = form.getFieldsValue();
    const params: any = { page: 1 };

    if (values.transactionNo) params.transactionNo = values.transactionNo;
    if (values.direction) params.direction = values.direction;
    if (values.transactionType) params.transactionType = values.transactionType;
    if (values.businessType) params.businessType = values.businessType;
    if (values.dateRange && values.dateRange.length === 2) {
      params.startDate = values.dateRange[0].format('YYYY-MM-DD');
      params.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }

    refresh(params);
  };

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

  const handleViewDetail = (record: PlatformTransaction) => {
    detailModal.open(record);
  };

  const columns: ColumnsType<PlatformTransaction> = [
    {
      title: '交易流水号',
      dataIndex: 'transaction_no',
      key: 'transaction_no',
      width: 180,
      fixed: 'left',
    },
    {
      title: '交易时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '交易方向',
      dataIndex: 'direction',
      key: 'direction',
      width: 100,
      render: (direction: string) => {
        const config = {
          income: { text: '收入', color: 'green' },
          expense: { text: '支出', color: 'red' },
        };
        const item = config[direction as keyof typeof config] || { text: direction, color: 'default' };
        return <Tag color={item.color}>{item.text}</Tag>;
      },
    },
    {
      title: '交易类型',
      dataIndex: 'transaction_type',
      key: 'transaction_type',
      width: 120,
    },
    {
      title: '业务类型',
      dataIndex: 'business_type',
      key: 'business_type',
      width: 120,
    },
    {
      title: '业务单号',
      dataIndex: 'business_no',
      key: 'business_no',
      width: 150,
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number, record: PlatformTransaction) => (
        <span style={{ color: record.direction === 'income' ? '#52c41a' : '#ff4d4f', fontWeight: 'bold' }}>
          {record.direction === 'income' ? '+' : '-'}{formatMoney(amount, '')}
        </span>
      ),
    },
    {
      title: '交易前余额',
      dataIndex: 'balance_before',
      key: 'balance_before',
      width: 120,
      render: (balance: number) => formatMoney(balance),
    },
    {
      title: '交易后余额',
      dataIndex: 'balance_after',
      key: 'balance_after',
      width: 120,
      render: (balance: number) => formatMoney(balance),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record: PlatformTransaction) => (
        <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>平台交易记录</h2>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Form form={form} layout="inline">
            <Form.Item name="transactionNo" label="流水号">
              <Input placeholder="请输入交易流水号" style={{ width: 180 }} />
            </Form.Item>
            <Form.Item name="direction" label="交易方向">
              <Select placeholder="请选择" style={{ width: 120 }} allowClear>
                <Select.Option value="income">收入</Select.Option>
                <Select.Option value="expense">支出</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="transactionType" label="交易类型">
              <Select placeholder="请选择" style={{ width: 150 }} allowClear>
                <Select.Option value="订单收入">订单收入</Select.Option>
                <Select.Option value="商家结算">商家结算</Select.Option>
                <Select.Option value="邀请返现">邀请返现</Select.Option>
                <Select.Option value="提现">提现</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="businessType" label="业务类型">
              <Select placeholder="请选择" style={{ width: 150 }} allowClear>
                <Select.Option value="order">订单</Select.Option>
                <Select.Option value="settlement">结算</Select.Option>
                <Select.Option value="invitation">邀请</Select.Option>
                <Select.Option value="withdraw">提现</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="dateRange" label="交易时间">
              <RangePicker style={{ width: 240 }} />
            </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={columns}
          dataSource={transactions}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1600 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      <Modal
        title="交易详情"
        open={detailModal.visible}
        onCancel={detailModal.close}
        footer={null}
        width={700}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="交易流水号">{detailModal.data.transaction_no}</Descriptions.Item>
            <Descriptions.Item label="账户ID">{detailModal.data.account_id}</Descriptions.Item>
            <Descriptions.Item label="交易方向">
              <Tag color={detailModal.data.direction === 'income' ? 'green' : 'red'}>
                {detailModal.data.direction === 'income' ? '收入' : '支出'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="交易金额">
              <span
                style={{
                  fontSize: 18,
                  fontWeight: 'bold',
                  color: detailModal.data.direction === 'income' ? '#52c41a' : '#ff4d4f',
                }}
              >
                {detailModal.data.direction === 'income' ? '+' : '-'}
                {formatMoney(detailModal.data.amount)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="交易前余额">{formatMoney(detailModal.data.balance_before)}</Descriptions.Item>
            <Descriptions.Item label="交易后余额">{formatMoney(detailModal.data.balance_after)}</Descriptions.Item>
            <Descriptions.Item label="交易类型">{detailModal.data.transaction_type}</Descriptions.Item>
            <Descriptions.Item label="业务类型">{detailModal.data.business_type}</Descriptions.Item>
            <Descriptions.Item label="业务ID">{detailModal.data.business_id}</Descriptions.Item>
            <Descriptions.Item label="业务单号">{detailModal.data.business_no}</Descriptions.Item>
            {detailModal.data.related_account_type && (
              <>
                <Descriptions.Item label="关联账户类型">
                  {detailModal.data.related_account_type === 'merchant' ? '商家' : '用户'}
                </Descriptions.Item>
                <Descriptions.Item label="关联账户ID">{detailModal.data.related_account_id}</Descriptions.Item>
              </>
            )}
            <Descriptions.Item label="备注">{detailModal.data.remark}</Descriptions.Item>
            <Descriptions.Item label="交易时间">{formatDateTime(detailModal.data.created_at)}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default PlatformTransactions;
