import React, { useState } from 'react';
import { Card, Table, Form, Select, DatePicker, Button, Space, Modal, Descriptions } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { getMerchantTransactions, getTransactionDetail } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import type { Transaction, TransactionType } from '@rent/shared-types';
import { TRANSACTION_TYPE_MAP, TRANSACTION_TYPE_OPTIONS } from '@rent/shared-types';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';
import { TransactionAmount } from '@/components/TransactionAmount';

const { RangePicker } = DatePicker;

interface TransactionDetail extends Transaction {
  beforeBalance: number;
  afterBalance: number;
  remark: string;
}

const Transactions: React.FC = () => {
  const [form] = Form.useForm();

  const {
    data: transactions,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    setParams,
    reset,
  } = useTableData<Transaction>({
    fetchFn: async (params) => {
      const res = await getMerchantTransactions(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 detailModal = useModal<TransactionDetail>();

  const handleSearch = () => {
    const values = form.getFieldsValue();
    const { dateRange, ...rest } = values;

    const params: any = { ...rest };

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

    setParams(params);
  };

  const handleReset = () => {
    form.resetFields();
    reset();
  };

  const handleViewDetail = async (id: number) => {
    try {
      const res = await getTransactionDetail(id);
      detailModal.open(res.data);
    } catch (error) {
      console.error('获取交易详情失败', error);
    }
  };

  const columns: ColumnsType<Transaction> = [
    {
      title: '交易ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '交易时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => TRANSACTION_TYPE_MAP[type as TransactionType]?.label || type,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number, record: Transaction) => (
        <TransactionAmount type={record.type} amount={amount} />
      ),
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => formatMoney(balance),
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record: Transaction) => (
        <Button type="link" size="small" onClick={() => handleViewDetail(record.id)}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>交易流水</h2>

      <Card style={{ marginBottom: 16 }}>
        <Form form={form} layout="inline">
          <Form.Item name="type" label="交易类型">
            <Select placeholder="请选择" style={{ width: 150 }} allowClear>
              {TRANSACTION_TYPE_OPTIONS.map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="交易时间">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          columns={columns}
          dataSource={transactions}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          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={600}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="交易ID">{detailModal.data.id}</Descriptions.Item>
            <Descriptions.Item label="交易时间">{formatDateTime(detailModal.data.createdAt)}</Descriptions.Item>
            <Descriptions.Item label="交易类型">
              {TRANSACTION_TYPE_MAP[detailModal.data.type]?.label || detailModal.data.type}
            </Descriptions.Item>
            <Descriptions.Item label="交易金额">
              <TransactionAmount type={detailModal.data.type} amount={detailModal.data.amount} />
            </Descriptions.Item>
            <Descriptions.Item label="交易前余额">{formatMoney(detailModal.data.beforeBalance)}</Descriptions.Item>
            <Descriptions.Item label="交易后余额">{formatMoney(detailModal.data.afterBalance)}</Descriptions.Item>
            <Descriptions.Item label="说明">{detailModal.data.description}</Descriptions.Item>
            {detailModal.data.orderId && (
              <Descriptions.Item label="关联订单">订单 #{detailModal.data.orderId}</Descriptions.Item>
            )}
            {detailModal.data.remark && (
              <Descriptions.Item label="备注">{detailModal.data.remark}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default Transactions;
