import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { Loader2, Bot } from "lucide-react";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

export function AiSettingsCard() {
    const { t } = useTranslation();
    const { toast } = useToast();

    // Fetch settings
    const { data: settings, isLoading } = useQuery<Record<string, string>>({
        queryKey: ['/api/admin/settings'],
    });

    const [provider, setProvider] = useState("openai");
    const [apiKey, setApiKey] = useState("");
    const [model, setModel] = useState("gpt-4o");
    const [baseUrl, setBaseUrl] = useState("");

    useEffect(() => {
        if (settings) {
            setProvider(settings.ai_provider || "openai");
            setApiKey(settings.ai_api_key || "");
            setModel(settings.ai_model || "gpt-4o");
            setBaseUrl(settings.ai_base_url || "");
        }
    }, [settings]);

    const mutation = useMutation({
        mutationFn: async (data: any) => {
            const res = await apiRequest("POST", "/api/admin/settings", data);
            return res.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['/api/admin/settings'] });
            toast({ title: "Settings saved" });
        },
        onError: () => {
            toast({ title: "Failed to save settings", variant: "destructive" });
        }
    });

    const handleSave = () => {
        mutation.mutate({
            ai_provider: provider,
            ai_api_key: apiKey,
            ai_model: model,
            ai_base_url: baseUrl
        });
    };

    if (isLoading) return <Loader2 className="animate-spin" />;

    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Bot className="w-5 h-5" />
                    {t('settings.ai.title')}
                </CardTitle>
                <CardDescription>{t('settings.ai.description')}</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="grid gap-2">
                    <Label>{t('settings.ai.provider')}</Label>
                    <Select value={provider} onValueChange={(v) => {
                        setProvider(v);
                        if (v === 'openai' && model === 'claude-3-5-sonnet') setModel('gpt-4o');
                        if (v === 'anthropic' && model === 'gpt-4o') setModel('claude-3-5-sonnet');
                        if (v === 'ollama') {
                            setBaseUrl('http://localhost:11434');
                            setModel('llama3');
                        }
                    }}>
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="openai">OpenAI</SelectItem>
                            <SelectItem value="anthropic">Anthropic</SelectItem>
                            <SelectItem value="google">Google Gemini</SelectItem>
                            <SelectItem value="ollama">Ollama (Local)</SelectItem>
                        </SelectContent>
                    </Select>
                </div>

                <div className="grid gap-2">
                    <Label>{t('settings.ai.apiKey')}</Label>
                    <Input
                        type="password"
                        value={apiKey}
                        onChange={(e) => setApiKey(e.target.value)}
                        placeholder={provider === 'ollama' ? 'Optional for Ollama' : 'sk-...'}
                    />
                </div>

                <div className="grid gap-2">
                    <Label>{t('settings.ai.model')}</Label>
                    <Input
                        value={model}
                        onChange={(e) => setModel(e.target.value)}
                        placeholder="e.g. gpt-4, claude-3-opus, llama3"
                    />
                </div>

                <div className="grid gap-2">
                    <Label>{t('settings.ai.baseUrl')}</Label>
                    <Input
                        value={baseUrl}
                        onChange={(e) => setBaseUrl(e.target.value)}
                        placeholder={provider === 'ollama' ? 'http://localhost:11434' : 'Optional override'}
                    />
                </div>
            </CardContent>
            <CardFooter>
                <Button onClick={handleSave} disabled={mutation.isPending}>
                    {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Save
                </Button>
            </CardFooter>
        </Card>
    );
}
