import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { Button, Space, Alert, Spin, Typography } from 'antd';
import axios from 'axios';
import {
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query';

const { Title } = Typography;

// 创建QueryClient实例
const queryClient = new QueryClient();

interface MigrationResponse {
  success: boolean;
  error?: string;
  failedResult?: any;
}

const MigrationsApp: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [migrationResult, setMigrationResult] = useState<MigrationResponse | null>(null);

  const runMigrations = async () => {
    try {
      setLoading(true);
      setMigrationResult(null);
      
      const response = await axios.get('/api/migrations');
      setMigrationResult(response.data);
    } catch (error: any) {
      setMigrationResult({
        success: false,
        error: error.response?.data?.error || '数据库迁移失败',
        failedResult: error.response?.data?.failedResult
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4">
      <Title level={3}>数据库迁移管理</Title>
      
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <Button 
          type="primary" 
          onClick={runMigrations}
          loading={loading}
          disabled={loading}
        >
          执行迁移
        </Button>

        {loading && <Spin tip="迁移执行中..." />}

        {migrationResult && (
          migrationResult.success ? (
            <Alert 
              message="迁移成功" 
              type="success" 
              showIcon 
            />
          ) : (
            <Alert 
              message="迁移失败"
              description={
                <>
                  <p>{migrationResult.error}</p>
                  {migrationResult.failedResult && (
                    <pre style={{ marginTop: 10 }}>
                      {JSON.stringify(migrationResult.failedResult, null, 2)}
                    </pre>
                  )}
                </>
              }
              type="error" 
              showIcon 
            />
          )
        )}
      </Space>
    </div>
  );
};

// 渲染应用
const root = createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <QueryClientProvider client={queryClient}>
    <MigrationsApp />
  </QueryClientProvider>
);