import React, { useState } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, message, Tag, Switch } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getBankCards, createBankCard, updateBankCard, deleteBankCard } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import { formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';

interface BankCard {
  id: number;
  cardName: string;
  bankName: string;
  bankAccount: string;
  accountName: string;
  isDefault: boolean;
  status: 'active' | 'inactive';
  remark?: string;
  createdAt: string;
  updatedAt: string;
}

const BankCards: React.FC = () => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const createModal = useModal();
  const editModal = useModal<BankCard>();

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

  const handleCreate = () => {
    form.resetFields();
    createModal.open();
  };

  const handleEdit = (record: BankCard) => {
    form.setFieldsValue({
      cardName: record.cardName,
      bankName: record.bankName,
      bankAccount: record.bankAccount,
      accountName: record.accountName,
      isDefault: record.isDefault,
      remark: record.remark,
    });
    editModal.open(record);
  };

  const handleDelete = (record: BankCard) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除银行卡"${record.cardName}"吗？`,
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteBankCard(record.id);
          message.success('删除成功');
          refresh();
        } catch (error: any) {
          message.error(error.response?.data?.message || '删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values: any) => {
    setSubmitting(true);
    try {
      if (editModal.data) {
        await updateBankCard(editModal.data.id, values);
        message.success('更新成功');
        editModal.close();
      } else {
        await createBankCard(values);
        message.success('添加成功');
        createModal.close();
      }
      form.resetFields();
      refresh();
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    } finally {
      setSubmitting(false);
    }
  };

  const columns: ColumnsType<BankCard> = [
    {
      title: '卡片名称',
      dataIndex: 'cardName',
      key: 'cardName',
      width: 150,
    },
    {
      title: '开户银行',
      dataIndex: 'bankName',
      key: 'bankName',
      width: 150,
    },
    {
      title: '银行账号',
      dataIndex: 'bankAccount',
      key: 'bankAccount',
      width: 200,
      render: (account: string) => {
        const masked = account.replace(/(\d{4})\d+(\d{4})/, '$1****$2');
        return masked;
      },
    },
    {
      title: '账户名称',
      dataIndex: 'accountName',
      key: 'accountName',
      width: 120,
    },
    {
      title: '默认卡',
      dataIndex: 'isDefault',
      key: 'isDefault',
      width: 100,
      render: (isDefault: boolean) => (
        <Tag color={isDefault ? 'green' : 'default'}>{isDefault ? '是' : '否'}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: BankCard) => (
        <Space>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>平台银行卡管理</h2>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            添加银行卡
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={bankCards}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      <Modal
        title={editModal.data ? '编辑银行卡' : '添加银行卡'}
        open={createModal.visible || editModal.visible}
        onCancel={() => {
          createModal.close();
          editModal.close();
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="cardName"
            label="卡片名称"
            rules={[{ required: true, message: '请输入卡片名称' }]}
          >
            <Input placeholder="例如：主账户、备用账户" />
          </Form.Item>
          <Form.Item
            name="bankName"
            label="开户银行"
            rules={[{ required: true, message: '请输入开户银行' }]}
          >
            <Input placeholder="例如：中国工商银行" />
          </Form.Item>
          <Form.Item
            name="bankAccount"
            label="银行账号"
            rules={[
              { required: true, message: '请输入银行账号' },
              { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号（16-19位数字）' },
            ]}
          >
            <Input placeholder="请输入银行账号" maxLength={19} />
          </Form.Item>
          <Form.Item
            name="accountName"
            label="账户名称"
            rules={[{ required: true, message: '请输入账户名称' }]}
          >
            <Input placeholder="请输入账户名称" />
          </Form.Item>
          <Form.Item name="isDefault" label="设为默认" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注信息（选填）" />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button
                onClick={() => {
                  createModal.close();
                  editModal.close();
                  form.resetFields();
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={submitting}>
                {editModal.data ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BankCards;
