'use client';

import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, CheckCircle, AlertTriangle } from 'lucide-react';

export default function SetIPPage() {
  const [clientIP, setClientIP] = useState('61-227-253-171');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string>('');
  const [error, setError] = useState<string>('');

  // 設置客戶端 IP
  const setClientIP = async () => {
    if (!clientIP.trim()) {
      setError('請輸入客戶端 IP 地址');
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('/api/set-client-ip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ clientIP: clientIP.trim() }),
      });
      
      const data = await response.json();
      
      if (data.success) {
        setMessage(data.message || '客戶端 IP 設置成功');
        setError('');
      } else {
        setError(data.error || '設置客戶端 IP 失敗');
      }
    } catch (err) {
      setError('設置錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 快速設置你的 IP
  const setYourIP = () => {
    setClientIP('61-227-253-171');
  };

  // 測試清理功能
  const testCleanup = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/ip-cleanup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'cleanup-current' }),
      });
      
      const data = await response.json();
      
      if (data.success) {
        setMessage(`清理完成: ${data.message}`);
        setError('');
      } else {
        setError(data.error || '清理失敗');
      }
    } catch (err) {
      setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold">設置客戶端 IP</h1>
        <p className="text-muted-foreground">
          手動設置你的真實 IP 地址，用於連線清理
        </p>
      </div>

      {/* IP 設置 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="h-5 w-5" />
            設置客戶端 IP
          </CardTitle>
          <CardDescription>
            輸入你的真實 IP 地址，系統將使用此 IP 來清理連線
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="clientIP">客戶端 IP 地址</Label>
            <div className="flex gap-2">
              <Input
                id="clientIP"
                value={clientIP}
                onChange={(e) => setClientIP(e.target.value)}
                placeholder="例如: 61-227-253-171"
                className="flex-1"
              />
              <Button 
                onClick={setYourIP} 
                disabled={loading}
                variant="outline"
              >
                使用你的 IP
              </Button>
            </div>
          </div>

          <div className="flex gap-2">
            <Button 
              onClick={setClientIP} 
              disabled={loading || !clientIP.trim()}
              className="flex-1"
            >
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle className="h-4 w-4" />}
              設置 IP
            </Button>
            
            <Button 
              onClick={testCleanup} 
              disabled={loading}
              variant="destructive"
              className="flex-1"
            >
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
              測試清理
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 使用說明 */}
      <Card>
        <CardHeader>
          <CardTitle>使用說明</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-sm text-muted-foreground">
          <p>• <strong>你的 IP:</strong> 61-227-253-171（從資料庫連線列表中獲取）</p>
          <p>• <strong>設置 IP:</strong> 點擊「設置 IP」按鈕來設置你的客戶端 IP</p>
          <p>• <strong>測試清理:</strong> 點擊「測試清理」按鈕來清理你的 IP 連線</p>
          <p>• <strong>自動清理:</strong> 設置後，關閉頁面時會自動清理你的 IP 連線</p>
        </CardContent>
      </Card>

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

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