'use client';

import { useState, useCallback } from 'react';
import { Modal, toast, Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import { useAppSelector } from '@/store/redux/hooks';
import {
  useSystemWithdrawalAccounts,
  useSystemWithdrawalOrders,
  useRequestSystemWithdrawal,
} from '@/hooks/useSystemWithdrawal';
import {
  SystemWithdrawalOrder,
  SystemWithdrawalStatus,
  SystemAccount,
  getSystemWithdrawalStatusInfo,
} from '@/types/system-withdrawal.types';
import { getAccountDisplayName } from '@/types';
import styles from './system-transfer.module.scss';

type TabType = 'transfer' | 'orders';

/**
 * 系统账户划转管理页面
 */
export default function SystemTransferPage() {
  // 获取当前登录用户
  const currentUser = useAppSelector((state) => state.auth.user);

  // 当前标签页
  const [activeTab, setActiveTab] = useState<TabType>('transfer');

  // 筛选状态
  const [filters, setFilters] = useState({
    fromAccountSequence: '',
    toAccountSequence: '',
    status: '' as SystemWithdrawalStatus | '',
    page: 1,
    limit: 20,
  });

  // 表单状态
  const [selectedAccount, setSelectedAccount] = useState<SystemAccount | null>(null);
  const [transferForm, setTransferForm] = useState({
    toAccountSequence: '',
    amount: '',
    memo: '',
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // 弹窗状态
  const [viewingOrder, setViewingOrder] = useState<SystemWithdrawalOrder | null>(null);
  const [confirmModalOpen, setConfirmModalOpen] = useState(false);

  // 数据查询
  const accountsQuery = useSystemWithdrawalAccounts();
  const ordersQuery = useSystemWithdrawalOrders({
    fromAccountSequence: filters.fromAccountSequence || undefined,
    toAccountSequence: filters.toAccountSequence || undefined,
    status: filters.status || undefined,
    page: filters.page,
    limit: filters.limit,
  });

  // Mutations
  const requestMutation = useRequestSystemWithdrawal();

  // 表单验证
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!selectedAccount) {
      errors.fromAccount = '请选择源账户';
    }

    if (!transferForm.toAccountSequence) {
      errors.toAccountSequence = '请输入目标账户序列号';
    } else if (!/^D\d{11}$/.test(transferForm.toAccountSequence)) {
      errors.toAccountSequence = '账户序列号格式不正确，应为 D + 11位数字';
    }

    if (!transferForm.amount) {
      errors.amount = '请输入划转金额';
    } else {
      const amount = parseFloat(transferForm.amount);
      if (isNaN(amount) || amount <= 0) {
        errors.amount = '请输入有效的金额';
      } else if (amount < 1) {
        errors.amount = '最小划转金额为 1 绿积分';
      }
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 提交划转请求
  const handleSubmitTransfer = async () => {
    if (!validateForm() || !selectedAccount) return;

    try {
      await requestMutation.mutateAsync({
        fromAccountSequence: selectedAccount.accountSequence,
        toAccountSequence: transferForm.toAccountSequence,
        amount: transferForm.amount,
        memo: transferForm.memo || undefined,
        operatorId: currentUser?.id || 'admin',
        operatorName: currentUser?.nickname || currentUser?.username,
      });
      toast.success('划转请求已提交，等待区块链确认');
      setConfirmModalOpen(false);
      // 重置表单
      setSelectedAccount(null);
      setTransferForm({ toAccountSequence: '', amount: '', memo: '' });
      setFormErrors({});
      // 切换到订单列表查看
      setActiveTab('orders');
    } catch (err: unknown) {
      // 从 Axios 错误中提取消息
      const axiosError = err as { response?: { data?: { message?: string } }; message?: string };
      const errorMessage = axiosError.response?.data?.message || axiosError.message || '划转失败';
      toast.error(errorMessage);
    }
  };

  // 打开确认弹窗
  const handleOpenConfirm = () => {
    if (validateForm()) {
      setConfirmModalOpen(true);
    }
  };

  // 搜索
  const handleSearch = useCallback(() => {
    setFilters((prev) => ({ ...prev, page: 1 }));
  }, []);

  // 翻页
  const handlePageChange = (page: number) => {
    setFilters((prev) => ({ ...prev, page }));
  };

  // 渲染账户选择卡片
  const renderAccountCards = () => {
    if (accountsQuery.isLoading) {
      return <div className={styles.systemTransfer__loading}>加载账户列表...</div>;
    }

    if (accountsQuery.error) {
      return (
        <div className={styles.systemTransfer__error}>
          <span>{(accountsQuery.error as Error).message || '加载失败'}</span>
          <Button variant="outline" size="sm" onClick={() => accountsQuery.refetch()}>
            重试
          </Button>
        </div>
      );
    }

    const accounts = accountsQuery.data || [];
    if (accounts.length === 0) {
      return <div className={styles.systemTransfer__empty}>暂无可划转账户</div>;
    }

    return (
      <div className={styles.systemTransfer__accountCards}>
        {accounts.map((account) => (
          <div
            key={account.accountSequence}
            className={cn(
              styles.systemTransfer__accountCard,
              selectedAccount?.accountSequence === account.accountSequence &&
                styles['systemTransfer__accountCard--selected']
            )}
            onClick={() => setSelectedAccount(account)}
          >
            {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
            <div className={styles.systemTransfer__accountCardName}>
              {getAccountDisplayName(account.accountSequence)}
            </div>
            {account.balance && (
              <div className={styles.systemTransfer__accountCardBalance}>
                余额: {parseFloat(account.balance).toFixed(2)} 绿积分
              </div>
            )}
          </div>
        ))}
      </div>
    );
  };

  // 渲染划转表单
  const renderTransferForm = () => {
    return (
      <>
        <div className={styles.systemTransfer__warning}>
          从系统账户划转资金到用户账户，资金将通过区块链转账，完成后会自动记录分类账。
        </div>

        <h3 style={{ marginBottom: '16px', fontSize: '16px' }}>1. 选择源账户</h3>
        {renderAccountCards()}
        {formErrors.fromAccount && (
          <div className={styles.systemTransfer__formError}>{formErrors.fromAccount}</div>
        )}

        <h3 style={{ marginBottom: '16px', fontSize: '16px' }}>2. 填写划转信息</h3>
        <div className={styles.systemTransfer__form}>
          <div className={styles.systemTransfer__formGroup}>
            <label>目标账户序列号 *</label>
            <input
              type="text"
              value={transferForm.toAccountSequence}
              onChange={(e) => {
                setTransferForm({ ...transferForm, toAccountSequence: e.target.value });
                setFormErrors({ ...formErrors, toAccountSequence: '' });
              }}
              placeholder="例如：D25121400005"
            />
            <div className={styles.systemTransfer__formHint}>输入用户的账户序列号（D开头+11位数字）</div>
            {formErrors.toAccountSequence && (
              <div className={styles.systemTransfer__formError}>{formErrors.toAccountSequence}</div>
            )}
          </div>

          <div className={styles.systemTransfer__formGroup}>
            <label>划转金额 (绿积分) *</label>
            <input
              type="number"
              value={transferForm.amount}
              onChange={(e) => {
                setTransferForm({ ...transferForm, amount: e.target.value });
                setFormErrors({ ...formErrors, amount: '' });
              }}
              placeholder="例如：100"
              min="1"
              step="0.01"
            />
            <div className={styles.systemTransfer__formHint}>最小划转金额为 1 绿积分</div>
            {formErrors.amount && (
              <div className={styles.systemTransfer__formError}>{formErrors.amount}</div>
            )}
          </div>

          <div className={styles.systemTransfer__formGroup}>
            <label>备注 (可选)</label>
            <textarea
              value={transferForm.memo}
              onChange={(e) => setTransferForm({ ...transferForm, memo: e.target.value })}
              placeholder="请输入划转备注..."
              rows={3}
            />
          </div>

          <div style={{ marginTop: '16px' }}>
            <Button
              variant="primary"
              onClick={handleOpenConfirm}
              disabled={!selectedAccount || !transferForm.toAccountSequence || !transferForm.amount}
            >
              提交划转
            </Button>
          </div>
        </div>
      </>
    );
  };

  // 渲染订单列表
  const renderOrderList = () => {
    const { data, isLoading, error, refetch } = ordersQuery;

    return (
      <>
        {/* 筛选区域 */}
        <div className={styles.systemTransfer__filters}>
          <input
            type="text"
            className={styles.systemTransfer__input}
            placeholder="源账户"
            value={filters.fromAccountSequence}
            onChange={(e) => setFilters({ ...filters, fromAccountSequence: e.target.value })}
          />
          <input
            type="text"
            className={styles.systemTransfer__input}
            placeholder="目标账户"
            value={filters.toAccountSequence}
            onChange={(e) => setFilters({ ...filters, toAccountSequence: e.target.value })}
          />
          <select
            className={styles.systemTransfer__select}
            value={filters.status}
            onChange={(e) =>
              setFilters({ ...filters, status: e.target.value as SystemWithdrawalStatus | '' })
            }
          >
            <option value="">全部状态</option>
            <option value="PENDING">待处理</option>
            <option value="FROZEN">已冻结</option>
            <option value="BROADCASTED">已广播</option>
            <option value="CONFIRMED">已确认</option>
            <option value="FAILED">失败</option>
          </select>
          <Button variant="outline" size="sm" onClick={handleSearch}>
            搜索
          </Button>
          <Button variant="outline" size="sm" onClick={() => refetch()}>
            刷新
          </Button>
        </div>

        {/* 列表 */}
        <div className={styles.systemTransfer__list}>
          {isLoading ? (
            <div className={styles.systemTransfer__loading}>加载中...</div>
          ) : error ? (
            <div className={styles.systemTransfer__error}>
              <span>{(error as Error).message || '加载失败'}</span>
              <Button variant="outline" size="sm" onClick={() => refetch()}>
                重试
              </Button>
            </div>
          ) : !data || data.items.length === 0 ? (
            <div className={styles.systemTransfer__empty}>暂无数据</div>
          ) : (
            <>
              {/* 表格 */}
              <table className={styles.systemTransfer__table}>
                <thead>
                  <tr>
                    <th>订单号</th>
                    <th>源账户</th>
                    <th>目标账户</th>
                    <th>金额</th>
                    <th>状态</th>
                    <th>TxHash</th>
                    <th>创建时间</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {data.items.map((order) => {
                    const statusInfo = getSystemWithdrawalStatusInfo(order.status);
                    return (
                      <tr key={order.orderNo}>
                        <td>
                          <div className={styles.systemTransfer__orderNo}>{order.orderNo}</div>
                        </td>
                        {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
                        <td>
                          <div className={styles.systemTransfer__accountSequence}>
                            {getAccountDisplayName(order.fromAccountSequence)}
                          </div>
                        </td>
                        <td>
                          <div className={styles.systemTransfer__accountSequence}>
                            {getAccountDisplayName(order.toAccountSequence)}
                          </div>
                          {order.toUserName && (
                            <div className={styles.systemTransfer__accountName}>
                              {order.toUserName}
                            </div>
                          )}
                        </td>
                        <td>
                          <div className={styles.systemTransfer__amount}>
                            {parseFloat(order.amount).toFixed(2)} 绿积分
                          </div>
                        </td>
                        <td>
                          <span
                            className={styles.systemTransfer__statusTag}
                            style={{ backgroundColor: statusInfo.color, color: 'white' }}
                          >
                            {statusInfo.label}
                          </span>
                        </td>
                        <td>
                          {order.txHash ? (
                            <div className={styles.systemTransfer__txHash} title={order.txHash}>
                              {order.txHash.slice(0, 10)}...
                            </div>
                          ) : (
                            <span style={{ color: '#999' }}>-</span>
                          )}
                        </td>
                        <td>{formatDateTime(order.createdAt)}</td>
                        <td>
                          <div className={styles.systemTransfer__actions}>
                            <button
                              className={styles.systemTransfer__actionBtn}
                              onClick={() => setViewingOrder(order)}
                            >
                              查看
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>

              {/* 分页 */}
              {data.total > filters.limit && (
                <div className={styles.systemTransfer__pagination}>
                  <span>
                    共 {data.total} 条，第 {data.page} / {Math.ceil(data.total / data.limit)} 页
                  </span>
                  <div className={styles.systemTransfer__pageButtons}>
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={data.page <= 1}
                      onClick={() => handlePageChange(data.page - 1)}
                    >
                      上一页
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={data.page >= Math.ceil(data.total / data.limit)}
                      onClick={() => handlePageChange(data.page + 1)}
                    >
                      下一页
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </>
    );
  };

  return (
    <PageContainer title="系统划转">
      <div className={styles.systemTransfer}>
        {/* 页面标题 */}
        <div className={styles.systemTransfer__header}>
          <h1 className={styles.systemTransfer__title}>系统账户划转</h1>
          <p className={styles.systemTransfer__subtitle}>
            从系统账户（总部、运营、积分股池等）划转资金到用户账户
          </p>
        </div>

        {/* 主内容卡片 */}
        <div className={styles.systemTransfer__card}>
          {/* 标签页 */}
          <div className={styles.systemTransfer__tabs}>
            <button
              className={cn(
                styles.systemTransfer__tab,
                activeTab === 'transfer' && styles['systemTransfer__tab--active']
              )}
              onClick={() => setActiveTab('transfer')}
            >
              发起划转
            </button>
            <button
              className={cn(
                styles.systemTransfer__tab,
                activeTab === 'orders' && styles['systemTransfer__tab--active']
              )}
              onClick={() => setActiveTab('orders')}
            >
              划转记录
            </button>
          </div>

          {/* 内容区域 */}
          {activeTab === 'transfer' ? renderTransferForm() : renderOrderList()}
        </div>

        {/* 查看详情弹窗 */}
        <Modal
          visible={!!viewingOrder}
          title="划转订单详情"
          onClose={() => setViewingOrder(null)}
          footer={
            <div className={styles.systemTransfer__modalFooter}>
              <Button variant="outline" onClick={() => setViewingOrder(null)}>
                关闭
              </Button>
            </div>
          }
          width={600}
        >
          {viewingOrder && (
            <div className={styles.systemTransfer__detail}>
              <div className={styles.systemTransfer__detailSection}>
                <div className={styles.systemTransfer__detailTitle}>订单信息</div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>订单号:</span>
                  <span className={styles.systemTransfer__detailValue}>{viewingOrder.orderNo}</span>
                </div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>金额:</span>
                  <span className={styles.systemTransfer__detailValue}>
                    {parseFloat(viewingOrder.amount).toFixed(2)} 绿积分
                  </span>
                </div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>状态:</span>
                  <span
                    className={styles.systemTransfer__statusTag}
                    style={{
                      backgroundColor: getSystemWithdrawalStatusInfo(viewingOrder.status).color,
                      color: 'white',
                    }}
                  >
                    {getSystemWithdrawalStatusInfo(viewingOrder.status).label}
                  </span>
                </div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>创建时间:</span>
                  <span className={styles.systemTransfer__detailValue}>
                    {formatDateTime(viewingOrder.createdAt)}
                  </span>
                </div>
              </div>

              {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
              <div className={styles.systemTransfer__detailSection}>
                <div className={styles.systemTransfer__detailTitle}>源账户</div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>账户:</span>
                  <span className={styles.systemTransfer__detailValue}>
                    {getAccountDisplayName(viewingOrder.fromAccountSequence)}
                  </span>
                </div>
              </div>

              <div className={styles.systemTransfer__detailSection}>
                <div className={styles.systemTransfer__detailTitle}>目标账户</div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>账户:</span>
                  <span className={styles.systemTransfer__detailValue}>
                    {getAccountDisplayName(viewingOrder.toAccountSequence)}
                  </span>
                </div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>用户ID:</span>
                  <span className={styles.systemTransfer__detailValue}>{viewingOrder.toUserId}</span>
                </div>
                {viewingOrder.toUserName && (
                  <div className={styles.systemTransfer__detailRow}>
                    <span className={styles.systemTransfer__detailLabel}>用户姓名:</span>
                    <span className={styles.systemTransfer__detailValue}>
                      {viewingOrder.toUserName}
                    </span>
                  </div>
                )}
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>钱包地址:</span>
                  <span
                    className={styles.systemTransfer__detailValue}
                    style={{ wordBreak: 'break-all' }}
                  >
                    {viewingOrder.toAddress}
                  </span>
                </div>
              </div>

              {(viewingOrder.txHash || viewingOrder.errorMessage) && (
                <div className={styles.systemTransfer__detailSection}>
                  <div className={styles.systemTransfer__detailTitle}>区块链信息</div>
                  {viewingOrder.txHash && (
                    <div className={styles.systemTransfer__detailRow}>
                      <span className={styles.systemTransfer__detailLabel}>TxHash:</span>
                      <span
                        className={styles.systemTransfer__detailValue}
                        style={{ wordBreak: 'break-all', fontFamily: 'monospace' }}
                      >
                        {viewingOrder.txHash}
                      </span>
                    </div>
                  )}
                  {viewingOrder.errorMessage && (
                    <div className={styles.systemTransfer__detailRow}>
                      <span className={styles.systemTransfer__detailLabel}>错误信息:</span>
                      <span className={styles.systemTransfer__detailValue} style={{ color: '#ff4d4f' }}>
                        {viewingOrder.errorMessage}
                      </span>
                    </div>
                  )}
                </div>
              )}

              {viewingOrder.memo && (
                <div className={styles.systemTransfer__detailSection}>
                  <div className={styles.systemTransfer__detailTitle}>备注</div>
                  <div className={styles.systemTransfer__detailRow}>
                    <span className={styles.systemTransfer__detailValue}>{viewingOrder.memo}</span>
                  </div>
                </div>
              )}

              <div className={styles.systemTransfer__detailSection}>
                <div className={styles.systemTransfer__detailTitle}>操作信息</div>
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>操作员:</span>
                  <span className={styles.systemTransfer__detailValue}>
                    {viewingOrder.operatorName || viewingOrder.operatorId}
                  </span>
                </div>
                {viewingOrder.frozenAt && (
                  <div className={styles.systemTransfer__detailRow}>
                    <span className={styles.systemTransfer__detailLabel}>冻结时间:</span>
                    <span className={styles.systemTransfer__detailValue}>
                      {formatDateTime(viewingOrder.frozenAt)}
                    </span>
                  </div>
                )}
                {viewingOrder.broadcastedAt && (
                  <div className={styles.systemTransfer__detailRow}>
                    <span className={styles.systemTransfer__detailLabel}>广播时间:</span>
                    <span className={styles.systemTransfer__detailValue}>
                      {formatDateTime(viewingOrder.broadcastedAt)}
                    </span>
                  </div>
                )}
                {viewingOrder.confirmedAt && (
                  <div className={styles.systemTransfer__detailRow}>
                    <span className={styles.systemTransfer__detailLabel}>确认时间:</span>
                    <span className={styles.systemTransfer__detailValue}>
                      {formatDateTime(viewingOrder.confirmedAt)}
                    </span>
                  </div>
                )}
              </div>
            </div>
          )}
        </Modal>

        {/* 确认划转弹窗 */}
        <Modal
          visible={confirmModalOpen}
          title="确认划转"
          onClose={() => setConfirmModalOpen(false)}
          footer={
            <div className={styles.systemTransfer__modalFooter}>
              <Button variant="outline" onClick={() => setConfirmModalOpen(false)}>
                取消
              </Button>
              <Button
                variant="primary"
                onClick={handleSubmitTransfer}
                loading={requestMutation.isPending}
              >
                确认划转
              </Button>
            </div>
          }
          width={500}
        >
          <div className={styles.systemTransfer__detail}>
            <div className={styles.systemTransfer__warning}>
              请仔细核对划转信息，划转一旦提交将无法撤销。
            </div>
            {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
            <div className={styles.systemTransfer__detailSection}>
              <div className={styles.systemTransfer__detailRow}>
                <span className={styles.systemTransfer__detailLabel}>源账户:</span>
                <span className={styles.systemTransfer__detailValue}>
                  {selectedAccount ? getAccountDisplayName(selectedAccount.accountSequence) : '-'}
                </span>
              </div>
              <div className={styles.systemTransfer__detailRow}>
                <span className={styles.systemTransfer__detailLabel}>目标账户:</span>
                <span className={styles.systemTransfer__detailValue}>
                  {getAccountDisplayName(transferForm.toAccountSequence)}
                </span>
              </div>
              <div className={styles.systemTransfer__detailRow}>
                <span className={styles.systemTransfer__detailLabel}>划转金额:</span>
                <span className={styles.systemTransfer__detailValue}>
                  {transferForm.amount} 绿积分
                </span>
              </div>
              {transferForm.memo && (
                <div className={styles.systemTransfer__detailRow}>
                  <span className={styles.systemTransfer__detailLabel}>备注:</span>
                  <span className={styles.systemTransfer__detailValue}>{transferForm.memo}</span>
                </div>
              )}
            </div>
          </div>
        </Modal>
      </div>
    </PageContainer>
  );
}
