import { useState, useEffect, useCallback } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {
  Card, Button, Space, Typography, Tag, Statistic, Row, Col,
  Alert, Tooltip, Collapse, message,
} from 'antd';
import {
  PlayCircleOutlined, PauseCircleOutlined, ReloadOutlined,
  CheckCircleOutlined, CloseCircleOutlined, ThunderboltOutlined,
} from '@ant-design/icons';
import {
  getLiquidationStatus, startLiquidationBot, stopLiquidationBot,
  listLiquidationRecords,
} from '@/services/admin/api';
import type { LiquidationBotStatus, LiquidationRecord } from '@/services/admin/api';

const { Text } = Typography;

export default function LiquidationPage() {
  const [status, setStatus] = useState<LiquidationBotStatus | null>(null);
  const [statusLoading, setStatusLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  const fetchStatus = useCallback(async () => {
    setStatusLoading(true);
    try {
      const res = await getLiquidationStatus();
      if (res.success) setStatus(res.data);
    } catch (err: any) {
      // ignore
    } finally {
      setStatusLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStatus();
    const timer = setInterval(fetchStatus, 10000); // auto-refresh every 10s
    return () => clearInterval(timer);
  }, [fetchStatus]);

  const handleStart = async () => {
    setActionLoading(true);
    try {
      const res = await startLiquidationBot();
      if (res.success) {
        message.success('机器人启动信号已发送');
        setTimeout(fetchStatus, 1500);
      } else {
        message.error(res.message || '启动失败');
      }
    } catch (e: any) {
      message.error(e?.message || '请求失败');
    } finally {
      setActionLoading(false);
    }
  };

  const handleStop = async () => {
    setActionLoading(true);
    try {
      const res = await stopLiquidationBot();
      if (res.success) {
        message.success('机器人停止信号已发送');
        setTimeout(fetchStatus, 1500);
      } else {
        message.error(res.message || '停止失败');
      }
    } catch (e: any) {
      message.error(e?.message || '请求失败');
    } finally {
      setActionLoading(false);
    }
  };

  const columns: ProColumns<LiquidationRecord>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 70,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (_, r) =>
        r.status === 'success' ? (
          <Tag icon={<CheckCircleOutlined />} color="success">成功</Tag>
        ) : (
          <Tag icon={<CloseCircleOutlined />} color="error">失败</Tag>
        ),
    },
    {
      title: '清算账户数',
      dataIndex: 'account_count',
      width: 100,
    },
    {
      title: 'Chain ID',
      dataIndex: 'chain_id',
      width: 90,
    },
    {
      title: '区块',
      dataIndex: 'block_number',
      width: 120,
    },
    {
      title: 'Gas 消耗',
      dataIndex: 'gas_used',
      width: 110,
      render: (v) => Number(v).toLocaleString(),
    },
    {
      title: '交易哈希',
      dataIndex: 'tx_hash',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '被清算地址',
      dataIndex: 'accounts',
      ellipsis: true,
      copyable: true,
      render: (_, r) => {
        try {
          const addrs: string[] = JSON.parse(r.accounts);
          return (
            <Tooltip title={addrs.join('\n')} styles={{ root: { whiteSpace: 'pre-line' } }}>
              <span style={{ cursor: 'pointer' }}>{addrs.length} 个地址</span>
            </Tooltip>
          );
        } catch (err: any) {
          return r.accounts;
        }
      },
    },
    {
      title: '错误信息',
      dataIndex: 'error_message',
      ellipsis: true,
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      width: 175,
      render: (v) => new Date(String(v)).toLocaleString('zh-CN'),
    },
  ];

  const isRunning = status?.running ?? false;

  return (
    <PageContainer title="清算机器人">
      {/* Status Card */}
      <Card
        title={
          <Space>
            <ThunderboltOutlined />
            机器人状态
          </Space>
        }
        extra={
          <Space>
            <Button
              icon={<ReloadOutlined />}
              loading={statusLoading}
              onClick={fetchStatus}
            >
              刷新
            </Button>
            {isRunning ? (
              <Button
                danger
                icon={<PauseCircleOutlined />}
                loading={actionLoading}
                onClick={handleStop}
              >
                停止机器人
              </Button>
            ) : (
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                loading={actionLoading}
                onClick={handleStart}
              >
                启动机器人
              </Button>
            )}
          </Space>
        }
        style={{ marginBottom: 16 }}
      >
        {status?.error && !isRunning && (
          <Alert
            type="warning"
            message={status.error}
            style={{ marginBottom: 16 }}
            showIcon
          />
        )}

        <Row gutter={[24, 16]}>
          <Col span={4}>
            <Statistic
              title="运行状态"
              value={isRunning ? '运行中' : '已停止'}
              valueStyle={{ color: isRunning ? '#52c41a' : '#ff4d4f', fontSize: 18 }}
              prefix={isRunning ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="累计清算账户"
              value={status?.total_liquidations ?? 0}
              suffix="个"
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="轮询间隔"
              value={(status?.loop_delay_ms ?? 5000) / 1000}
              suffix="秒"
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="最新检查区块"
              value={status?.last_block_checked ?? '-'}
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="Chain ID"
              value={status?.chain_id ?? '-'}
            />
          </Col>
        </Row>

        {status && (
          <Collapse
            ghost
            style={{ marginTop: 16 }}
            items={[
              {
                key: '1',
                label: '详细配置',
                children: (
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 24px', fontSize: 13 }}>
                    <div><Text type="secondary">清算者地址：</Text><Text copyable>{status.liquidator_addr || '-'}</Text></div>
                    <div><Text type="secondary">Lending 合约：</Text><Text copyable>{status.contract_addr || '-'}</Text></div>
                    <div><Text type="secondary">回溯区块数：</Text><Text>{status.lookback_blocks.toLocaleString()}</Text></div>
                    <div>
                      <Text type="secondary">最后检查时间：</Text>
                      <Text>
                        {status.last_check_time && status.last_check_time !== '0001-01-01T00:00:00Z'
                          ? new Date(status.last_check_time).toLocaleString('zh-CN')
                          : '-'}
                      </Text>
                    </div>
                  </div>
                ),
              },
            ]}
          />
        )}
      </Card>

      {/* Liquidation Records */}
      <ProTable<LiquidationRecord>
        headerTitle="清算记录"
        rowKey="id"
        columns={columns}
        request={async (params) => {
          const res = await listLiquidationRecords({
            current: params.current,
            pageSize: params.pageSize,
            chain_id: params.chain_id,
            status: params.status,
          });
          return {
            data: res.data ?? [],
            total: res.total ?? 0,
            success: res.success,
          };
        }}
        pagination={{ pageSize: 20, showSizeChanger: true }}
        search={false}
        options={{ reload: true, density: false, setting: false }}
        scroll={{ x: 1200 }}
      />
    </PageContainer>
  );
}
