'use client';

import React, { useState, useEffect } from 'react';
import { Key, ExternalLink, Check, Loader2 } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SettingCard } from "@/components/ui/setting-card";
import { DefaultService } from "@/lib/api";
import { ProviderIcon } from "@/components/common/ProviderIcon";

// 简单的辅助函数：首字母大写
const capitalize = (s: string) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';

interface KeysTabProps {
    config: any;
    setConfig: (config: any) => void;
}

interface ApiKeyConfig {
    key: string;
    label: string;
    providerId: string;
    description: string;
    link?: string;
    placeholder?: string;
}

const ApiKeyCard: React.FC<{ config: ApiKeyConfig }> = ({ config }) => {
    const [value, setValue] = useState('');
    const [isSaved, setIsSaved] = useState(false);

    useEffect(() => {
        const stored = localStorage.getItem(config.key);
        if (stored) setValue(stored);
    }, [config.key]);

    const handleSave = () => {
        localStorage.setItem(config.key, value.trim());
        setIsSaved(true);
        setTimeout(() => setIsSaved(false), 2000);
    };

    return (
        <SettingCard
            title={
                <div className="flex items-center gap-2">
                    <div className="w-5 h-5 rounded-full overflow-hidden shrink-0 p-0.5 bg-muted/20">
                         <ProviderIcon provider={config.providerId} />
                    </div>
                    <div className="flex items-center gap-1">
                        <span>{config.label}</span>
                        {config.link && (
                            <a 
                                href={config.link}
                                target="_blank" 
                                rel="noreferrer" 
                                className="text-muted-foreground hover:text-primary transition-colors"
                                title="获取 Key"
                            >
                                <ExternalLink size={14} />
                            </a>
                        )}
                    </div>
                </div>
            }
            description={config.description}
            action={
                isSaved ? (
                    <span className="flex items-center gap-1 text-xs font-medium text-green-500 bg-green-500/10 px-2 py-1 rounded-full animate-in fade-in">
                        <Check size={12} />
                        已保存
                    </span>
                ) : (
                     value && value !== localStorage.getItem(config.key) ? (
                        <span className="text-[10px] text-amber-500 bg-amber-500/10 px-2 py-1 rounded-full">
                            未保存
                        </span>
                     ) : null
                )
            }
            footer={
                <span>仅存储在本地浏览器，不上传服务器</span>
            }
        >
            <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none z-10">
                    <Key size={14} className="text-muted-foreground/50" />
                </div>
                <Input 
                    type="password" 
                    autoComplete="off"
                    className="pl-9 pr-20 font-mono"
                    placeholder={config.placeholder}
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                />
                <div className="absolute inset-y-1 right-1 z-10">
                    <Button 
                        onClick={handleSave}
                        size="sm"
                        variant="ghost"
                        className="h-full px-3 hover:bg-background hover:text-primary text-xs font-medium text-muted-foreground"
                    >
                        保存
                    </Button>
                </div>
            </div>
        </SettingCard>
    );
};

export const KeysTab: React.FC<KeysTabProps> = ({ config, setConfig }) => {
    const [providers, setProviders] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchProviders = async () => {
            try {
                const res = await DefaultService.getProviders();
                if (res.data?.providers) {
                    // Filter providers that have api_key_name configured
                    const apiKeyProviders = res.data.providers.filter((p: any) => p.api_key_name);
                    setProviders(apiKeyProviders);
                }
            } catch (error) {
                console.error("Failed to fetch providers:", error);
            } finally {
                setIsLoading(false);
            }
        };
        fetchProviders();
    }, []);

    if (isLoading) {
        return <div className="flex justify-center p-8"><Loader2 className="animate-spin text-muted-foreground" /></div>;
    }

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
            {/* Header */}
            <div className="flex items-center gap-2">
                <h3 className="text-lg font-medium">API 密钥管理</h3>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {providers.map((provider) => (
                    <ApiKeyCard
                        key={provider.id}
                        config={{
                            key: provider.api_key_name,
                            label: provider.name || capitalize(provider.id),
                            providerId: provider.id,
                            description: provider.description || '',
                            link: provider.dashboard_url,
                            placeholder: '...'
                        }}
                    />
                ))}
            </div>
            
            <div className="rounded-lg bg-blue-50 dark:bg-blue-900/10 border border-blue-100 dark:border-blue-900/20 p-4">
                <div className="space-y-1">
                    <h4 className="text-sm font-medium text-blue-900 dark:text-blue-300">关于 API 密钥安全</h4>
                    <p className="text-xs text-blue-700 dark:text-blue-400 leading-relaxed">
                        您的 API 密钥仅保存在当前浏览器的 LocalStorage 中，直接用于前端向模型服务商发起请求（如果支持前端调用）或通过后端代理转发。Pixel 不会收集或在服务器端持久化存储您的密钥。请确保您使用的是受信任的设备。
                    </p>
                </div>
            </div>
        </div>
    );
};
