'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, Eye, RefreshCw } from 'lucide-react';

interface IPInfo {
  smartDetection?: {
    detectedIP: string;
    confidence: 'high' | 'medium' | 'low';
    source: string;
    allCandidates: string[];
    isPublicIP: boolean;
  };
  headers: Record<string, string | null>;
  nextRequestIP: string | undefined;
  env: Record<string, string | undefined>;
  allHeaders: Record<string, string>;
}

export default function DebugIPPage() {
  const [ipInfo, setIpInfo] = useState<IPInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string>('');
  const [error, setError] = useState<string>('');
  const [recommendedIP, setRecommendedIP] = useState<string>('');

  // 獲取 IP 調試信息
  const fetchIPInfo = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/debug-ip');
      const data = await response.json();
      
      if (data.success) {
        setIpInfo(data.data);
        
        // 提取智能偵測結果
        if (data.data.smartDetection) {
          const smartDetection = data.data.smartDetection;
          setRecommendedIP(smartDetection.detectedIP);
          setMessage(`智能偵測結果: ${smartDetection.detectedIP} (可信度: ${smartDetection.confidence}, 來源: ${smartDetection.source})`);
        } else {
          setMessage('IP 調試信息更新成功');
        }
        setError('');
      } else {
        setError(data.error || '獲取 IP 調試信息失敗');
      }
    } catch (err) {
      setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 組件載入時獲取 IP 信息
  useEffect(() => {
    fetchIPInfo();
  }, []);

  // 獲取推薦的 IP
  const getRecommendedIP = () => {
    if (!ipInfo) return 'unknown';
    
    // 優先使用智能偵測結果
    if (ipInfo.smartDetection) {
      return ipInfo.smartDetection.detectedIP;
    }
    
    // 回退到舊的邏輯
    const { headers, nextRequestIP } = ipInfo;
    
    // 優先順序檢查
    if (headers['cf-connecting-ip']) return headers['cf-connecting-ip'];
    if (headers['x-real-ip']) return headers['x-real-ip'];
    if (headers['x-client-ip']) return headers['x-client-ip'];
    if (headers['x-cluster-client-ip']) return headers['x-cluster-client-ip'];
    if (headers['x-forwarded']) return headers['x-forwarded'];
    if (headers['x-forwarded-for']) {
      const ips = headers['x-forwarded-for']!.split(',').map(ip => ip.trim());
      const publicIPs = ips.filter(ip => 
        ip && 
        ip !== '127.0.0.1' && 
        ip !== '::1' && 
        !ip.startsWith('192.168.') &&
        !ip.startsWith('10.') &&
        !ip.startsWith('172.')
      );
      if (publicIPs.length > 0) return publicIPs[0];
      return ips[0];
    }
    if (nextRequestIP && nextRequestIP !== '::1' && nextRequestIP !== '127.0.0.1') {
      return nextRequestIP;
    }
    
    return 'unknown';
  };

  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">IP 調試工具</h1>
          <p className="text-muted-foreground">
            調試和檢查客戶端 IP 地址獲取
          </p>
        </div>
        <Button 
          onClick={fetchIPInfo} 
          disabled={loading}
          variant="outline"
        >
          {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
          重新整理
        </Button>
      </div>

      {/* 智能偵測結果 */}
      {ipInfo?.smartDetection && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5" />
              智能 IP 偵測結果
            </CardTitle>
            <CardDescription>
              使用智能算法偵測的客戶端 IP 地址
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-4">
              <Badge 
                variant={ipInfo.smartDetection.isPublicIP ? "default" : "secondary"} 
                className="text-lg px-3 py-1"
              >
                {ipInfo.smartDetection.detectedIP}
              </Badge>
              <Badge 
                variant={
                  ipInfo.smartDetection.confidence === 'high' ? "default" :
                  ipInfo.smartDetection.confidence === 'medium' ? "secondary" : "destructive"
                }
                className="text-lg px-3 py-1"
              >
                可信度: {ipInfo.smartDetection.confidence}
              </Badge>
              <Badge variant="outline" className="text-lg px-3 py-1">
                來源: {ipInfo.smartDetection.source}
              </Badge>
            </div>
            
            {ipInfo.smartDetection.allCandidates.length > 1 && (
              <div>
                <p className="text-sm font-medium mb-2">所有候選 IP:</p>
                <div className="flex flex-wrap gap-2">
                  {ipInfo.smartDetection.allCandidates.map((ip, index) => (
                    <Badge 
                      key={index} 
                      variant={ip === ipInfo.smartDetection.detectedIP ? "default" : "outline"}
                      className="text-sm"
                    >
                      {ip}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 推薦的 IP (回退顯示) */}
      {ipInfo && !ipInfo.smartDetection && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5" />
              推薦的 IP 地址
            </CardTitle>
            <CardDescription>
              系統推薦使用的客戶端 IP 地址
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-4">
              <Badge variant="default" className="text-lg px-3 py-1">
                {getRecommendedIP()}
              </Badge>
              <Badge 
                variant={getRecommendedIP() === 'unknown' ? "destructive" : "default"}
                className="text-lg px-3 py-1"
              >
                狀態: {getRecommendedIP() === 'unknown' ? "無法識別" : "已識別"}
              </Badge>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 請求標頭 */}
      {ipInfo && (
        <Card>
          <CardHeader>
            <CardTitle>請求標頭</CardTitle>
            <CardDescription>
              從 HTTP 請求標頭中獲取的 IP 相關信息
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {Object.entries(ipInfo.headers).map(([key, value]) => (
                <div key={key} className="flex items-center justify-between p-2 border rounded">
                  <span className="font-medium text-sm">{key}:</span>
                  <span className="text-sm text-muted-foreground">
                    {value || 'null'}
                  </span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* NextRequest IP */}
      {ipInfo && (
        <Card>
          <CardHeader>
            <CardTitle>NextRequest IP</CardTitle>
            <CardDescription>
              Next.js 框架提供的 IP 地址
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-4">
              <Badge variant="outline" className="text-lg px-3 py-1">
                {ipInfo.nextRequestIP || 'undefined'}
              </Badge>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 環境信息 */}
      {ipInfo && (
        <Card>
          <CardHeader>
            <CardTitle>環境信息</CardTitle>
            <CardDescription>
              部署環境相關信息
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {Object.entries(ipInfo.env).map(([key, value]) => (
                <div key={key} className="flex items-center justify-between p-2 border rounded">
                  <span className="font-medium text-sm">{key}:</span>
                  <span className="text-sm text-muted-foreground">
                    {value || 'undefined'}
                  </span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 所有標頭（用於調試） */}
      {ipInfo && (
        <Card>
          <CardHeader>
            <CardTitle>所有請求標頭</CardTitle>
            <CardDescription>
              完整的 HTTP 請求標頭信息
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {Object.entries(ipInfo.allHeaders).map(([key, value]) => (
                <div key={key} className="flex items-center justify-between p-2 border rounded text-xs">
                  <span className="font-medium">{key}:</span>
                  <span className="text-muted-foreground break-all">
                    {value}
                  </span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

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

      {error && (
        <Alert variant="destructive">
          <Eye 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>推薦的 IP:</strong> 系統根據優先順序推薦使用的 IP 地址</p>
          <p>• <strong>請求標頭:</strong> 檢查各種代理和負載均衡器設置的 IP 標頭</p>
          <p>• <strong>NextRequest IP:</strong> Next.js 框架直接提供的 IP 地址</p>
          <p>• <strong>環境信息:</strong> 部署環境相關的配置信息</p>
          <p>• 如果推薦的 IP 是 "unknown"，請檢查代理設置或網路配置</p>
        </CardContent>
      </Card>
    </div>
  );
}
