'use client';

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap } from 'lucide-react';

interface ConnectionDetail {
  ID: number;
  USER: string;
  HOST: string;
  DB: string;
  COMMAND: string;
  TIME: number;
  STATE: string;
  INFO?: string;
}

interface ConnectionData {
  connectionCount: number;
  connections: ConnectionDetail[];
}

export default function EmergencyCleanupPage() {
  const [connectionData, setConnectionData] = useState<ConnectionData | null>(null);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string>('');
  const [error, setError] = useState<string>('');

  // 獲取連線詳情
  const fetchConnectionDetails = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/emergency-cleanup?action=details');
      const data = await response.json();
      
      if (data.success) {
        setConnectionData(data.data);
        setMessage('連線詳情更新成功');
        setError('');
      } else {
        setError(data.error || '獲取連線詳情失敗');
      }
    } catch (err) {
      setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 執行緊急清理
  const executeEmergencyCleanup = async () => {
    if (!confirm('確定要執行緊急清理嗎？這會關閉所有資料庫連線！')) {
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('/api/emergency-cleanup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'cleanup' }),
      });
      
      const data = await response.json();
      
      if (data.success) {
        setMessage('緊急清理完成');
        setError('');
        await fetchConnectionDetails(); // 重新獲取詳情
      } else {
        setError(data.error || '緊急清理失敗');
      }
    } catch (err) {
      setError('緊急清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 強制殺死所有連線
  const forceKillAllConnections = async () => {
    if (!confirm('確定要強制殺死所有連線嗎？這會立即終止所有資料庫連線！')) {
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('/api/emergency-cleanup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'kill-all' }),
      });
      
      const data = await response.json();
      
      if (data.success) {
        setMessage('強制殺死連線完成');
        setError('');
        await fetchConnectionDetails(); // 重新獲取詳情
      } else {
        setError(data.error || '強制殺死連線失敗');
      }
    } catch (err) {
      setError('強制殺死連線錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 組件載入時獲取連線詳情
  useEffect(() => {
    fetchConnectionDetails();
  }, []);

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-red-600">緊急連線清理</h1>
          <p className="text-muted-foreground">
            緊急清理和強制關閉資料庫連線
          </p>
        </div>
        <Button 
          onClick={fetchConnectionDetails} 
          disabled={loading}
          variant="outline"
        >
          {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
          重新整理
        </Button>
      </div>

      {/* 警告提示 */}
      <Alert variant="destructive">
        <AlertTriangle className="h-4 w-4" />
        <AlertDescription>
          <strong>警告：</strong> 這些操作會立即關閉所有資料庫連線，可能影響正在運行的應用程式。請謹慎使用！
        </AlertDescription>
      </Alert>

      {/* 連線統計 */}
      {connectionData && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Database className="h-5 w-5" />
              當前連線狀態
            </CardTitle>
            <CardDescription>
              資料庫連線的詳細信息
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-4">
              <Badge variant="outline" className="text-lg px-3 py-1">
                總連線數: {connectionData.connectionCount}
              </Badge>
              <Badge 
                variant={connectionData.connectionCount > 10 ? "destructive" : "default"}
                className="text-lg px-3 py-1"
              >
                狀態: {connectionData.connectionCount > 10 ? "異常" : "正常"}
              </Badge>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 緊急操作 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-red-600">
            <Zap className="h-5 w-5" />
            緊急操作
          </CardTitle>
          <CardDescription>
            立即清理和關閉資料庫連線
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Button 
              onClick={executeEmergencyCleanup} 
              disabled={loading}
              variant="destructive"
              className="w-full"
            >
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
              緊急清理連線
            </Button>
            
            <Button 
              onClick={forceKillAllConnections} 
              disabled={loading}
              variant="destructive"
              className="w-full"
            >
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
              強制殺死所有連線
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 連線詳情列表 */}
      {connectionData && connectionData.connections.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>連線詳情列表</CardTitle>
            <CardDescription>
              當前所有資料庫連線的詳細信息
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {connectionData.connections.map((conn, index) => (
                <div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
                  <div className="flex items-center gap-4">
                    <Badge variant="outline">#{conn.ID}</Badge>
                    <div>
                      <p className="text-sm font-medium">
                        用戶: {conn.USER} | 主機: {conn.HOST}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        資料庫: {conn.DB} | 命令: {conn.COMMAND}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        時間: {conn.TIME}s | 狀態: {conn.STATE}
                      </p>
                      {conn.INFO && (
                        <p className="text-xs text-muted-foreground mt-1">
                          查詢: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 訊息顯示 */}
      {message && (
        <Alert>
          <Database className="h-4 w-4" />
          <AlertDescription>{message}</AlertDescription>
        </Alert>
      )}

      {error && (
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* 使用說明 */}
      <Card>
        <CardHeader>
          <CardTitle>使用說明</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-sm text-muted-foreground">
          <p>• <strong>緊急清理連線:</strong> 停止監控並關閉所有連線池，這是較溫和的方式</p>
          <p>• <strong>強制殺死所有連線:</strong> 直接殺死資料庫中的所有連線，這是更激進的方式</p>
          <p>• <strong>重新整理:</strong> 獲取最新的連線狀態和詳情</p>
          <p>• 建議先嘗試「緊急清理連線」，如果無效再使用「強制殺死所有連線」</p>
        </CardContent>
      </Card>
    </div>
  );
}
