'use client';
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';

const SimpleAPITestPage: React.FC = () => {
    const [response, setResponse] = useState<string>('');
    const [error, setError] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const [apiEndpoint, setApiEndpoint] = useState<string>('textures'); // 默认测试textures端点
    const [userId, setUserId] = useState<string>('1'); // 默认用户ID
    const [textureName, setTextureName] = useState<string>('');
    const [profileId, setProfileId] = useState<string>('1'); // 默认角色ID

    // 执行API测试
    const executeAPITest = async () => {
        try {
            setLoading(true);
            setError('');
            setResponse('');
            
            let url = '';
            
            // 根据选择的端点构建URL
            switch (apiEndpoint) {
                case 'user-profiles':
                    url = `/api/user-profiles?userId=${userId}`;
                    break;
                case 'profile':
                    url = `/api/profile?profileId=${profileId}`;
                    break;
                case 'profile-props':
                    url = `/api/profile-props?profileId=${profileId}`;
                    break;
                case 'textures':
                    url = textureName ? 
                        `/api/textures?name=${encodeURIComponent(textureName)}` : 
                        '/api/textures';
                    break;
                default:
                    throw new Error('未知的API端点');
            }
            
            console.log(`正在请求: ${url}`);
            
            const res = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            
            if (!res.ok) {
                throw new Error(`HTTP错误! 状态码: ${res.status}`);
            }
            
            const data = await res.json();
            setResponse(JSON.stringify(data, null, 2));
        } catch (err) {
            setError(`请求失败: ${err instanceof Error ? err.message : String(err)}`);
        } finally {
            setLoading(false);
        }
    };

    // 渲染参数输入表单
    const renderParamsForm = () => {
        switch (apiEndpoint) {
            case 'user-profiles':
                return (
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="userId">用户ID</Label>
                            <Input
                                id="userId"
                                value={userId}
                                onChange={(e) => setUserId(e.target.value)}
                                placeholder="输入用户ID"
                            />
                        </div>
                    </div>
                );
            case 'profile':
            case 'profile-props':
                return (
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="profileId">角色ID</Label>
                            <Input
                                id="profileId"
                                value={profileId}
                                onChange={(e) => setProfileId(e.target.value)}
                                placeholder="输入角色ID"
                            />
                        </div>
                    </div>
                );
            case 'textures':
                return (
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="textureName">材质名称 (可选)</Label>
                            <Input
                                id="textureName"
                                value={textureName}
                                onChange={(e) => setTextureName(e.target.value)}
                                placeholder="输入材质名称进行搜索"
                            />
                        </div>
                    </div>
                );
            default:
                return null;
        }
    };

    return (
        <div className="container mx-auto px-4 py-8">
            <h1 className="text-3xl font-bold mb-6">简易API测试页面</h1>
            <Card>
                <CardHeader>
                    <CardTitle>测试后端API连接</CardTitle>
                    <CardDescription>
                        选择要测试的API端点，输入必要的参数，然后点击"执行测试"按钮
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <div className="space-y-6">
                        {/* API端点选择 */}
                        <div className="space-y-2">
                            <Label>选择API端点</Label>
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                                <Button
                                    variant={apiEndpoint === 'user-profiles' ? "default" : "secondary"}
                                    onClick={() => setApiEndpoint('user-profiles')}
                                    className="justify-start text-sm"
                                >
                                    用户角色列表
                                </Button>
                                <Button
                                    variant={apiEndpoint === 'profile' ? "default" : "secondary"}
                                    onClick={() => setApiEndpoint('profile')}
                                    className="justify-start text-sm"
                                >
                                    角色详情
                                </Button>
                                <Button
                                    variant={apiEndpoint === 'profile-props' ? "default" : "secondary"}
                                    onClick={() => setApiEndpoint('profile-props')}
                                    className="justify-start text-sm"
                                >
                                    角色及属性
                                </Button>
                                <Button
                                    variant={apiEndpoint === 'textures' ? "default" : "secondary"}
                                    onClick={() => setApiEndpoint('textures')}
                                    className="justify-start text-sm"
                                >
                                    材质列表
                                </Button>
                            </div>
                        </div>

                        {/* 参数输入表单 */}
                        {renderParamsForm()}

                        {/* 执行按钮 */}
                        <Button
                            onClick={executeAPITest}
                            disabled={loading}
                            className="w-full"
                        >
                            {loading ? '执行中...' : '执行测试'}
                        </Button>

                        {/* 结果显示区域 */}
                        {(response || error) && (
                            <div className="mt-4 p-4 rounded-md border text-sm"
                                style={{
                                    borderColor: error ? 'rgb(248 113 113)' : 'rgb(203 213 225)',
                                    backgroundColor: error ? 'rgb(254 242 242)' : 'rgb(248 250 252)'
                                }}
                            >
                                {error ? (
                                    <div className="text-red-600 dark:text-red-400">
                                        {error}
                                    </div>
                                ) : (
                                    <pre className="whitespace-pre-wrap overflow-auto">
                                        {response}
                                    </pre>
                                )}
                            </div>
                        )}
                    </div>
                </CardContent>
                <CardFooter>
                    <p className="text-sm text-gray-500">
                        测试结果将显示在上方区域
                    </p>
                </CardFooter>
            </Card>
        </div>
    );
};

export default SimpleAPITestPage;