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 { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { Loader2, Bot, RefreshCw, Download, Server } 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("");
    const [systemPrompt, setSystemPrompt] = useState("");

    // Ollama specific state
    const [ollamaModels, setOllamaModels] = useState<string[]>([]);
    const [pullModelName, setPullModelName] = 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 || "");
            setSystemPrompt(settings.ai_system_prompt || "");
        }
    }, [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: t('settings.ai.saved', "Settings saved") });
        },
        onError: () => {
            toast({ title: t('settings.ai.error', "Failed to save settings"), variant: "destructive" });
        }
    });

    const fetchOllamaModelsMutation = useMutation({
        mutationFn: async () => {
            const res = await apiRequest("POST", "/api/admin/ollama/tags", { baseUrl });
            if (!res.ok) throw new Error("Failed to fetch models");
            return res.json();
        },
        onSuccess: (data: any) => {
            const models = data.models?.map((m: any) => m.name) || [];
            setOllamaModels(models);
            toast({ title: t('settings.ai.ollama.found', { count: models.length }) });
        },
        onError: (err: Error) => {
            toast({ title: t('settings.ai.ollama.connectError', "Could not connect to Ollama"), description: err.message, variant: "destructive" });
        }
    });

    const pullOllamaModelMutation = useMutation({
        mutationFn: async () => {
            const res = await apiRequest("POST", "/api/admin/ollama/pull", { baseUrl, model: pullModelName });
            if (!res.ok) throw new Error(await res.text());
            return res.json();
        },
        onSuccess: () => {
            toast({ title: t('settings.ai.ollama.pullSuccess', "Model pulled successfully") });
            setPullModelName("");
            fetchOllamaModelsMutation.mutate(); // Refresh list
        },
        onError: (err: Error) => {
            toast({ title: t('settings.ai.ollama.pullError', "Failed to pull model"), description: err.message, variant: "destructive" });
        }
    });


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

    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(baseUrl || 'http://localhost:11434');
                            if (!ollamaModels.length) setModel('llama3'); // Default if unknown
                        }
                    }}>
                        <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' ? t('settings.ai.ollama.placeholder', 'Optional for Ollama') : 'sk-...'}
                    />
                </div>

                <div className="grid gap-2">
                    <Label>{t('settings.ai.baseUrl')}</Label>
                    <div className="flex gap-2">
                        <Input
                            value={baseUrl}
                            onChange={(e) => setBaseUrl(e.target.value)}
                            placeholder={provider === 'ollama' ? 'http://localhost:11434' : 'Optional override'}
                        />
                        {provider === 'ollama' && (
                            <Button
                                variant="outline"
                                size="icon"
                                onClick={() => fetchOllamaModelsMutation.mutate()}
                                disabled={fetchOllamaModelsMutation.isPending}
                                title="Fetch Models from Server"
                            >
                                {fetchOllamaModelsMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
                            </Button>
                        )}
                    </div>
                </div>

                <div className="grid gap-2">
                    <Label>{t('settings.ai.model')}</Label>
                    {provider === 'ollama' && ollamaModels.length > 0 ? (
                        <div className="flex gap-2">
                            <Select value={model} onValueChange={setModel}>
                                <SelectTrigger className="flex-1">
                                    <SelectValue placeholder="Select a model" />
                                </SelectTrigger>
                                <SelectContent>
                                    {ollamaModels.map(m => (
                                        <SelectItem key={m} value={m}>{m}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    ) : (
                        <Input
                            value={model}
                            onChange={(e) => setModel(e.target.value)}
                            placeholder="e.g. gpt-4, llama3"
                        />
                    )}
                </div>

                {provider === 'ollama' && (
                    <div className="pt-4 border-t space-y-3">
                        <Label className="text-sm font-medium flex items-center gap-2">
                            <Download className="w-4 h-4" />
                            Pull Model from Ollama Library
                        </Label>
                        <div className="flex gap-2">
                            <Input
                                placeholder="Model name (e.g. llama3, mistral)"
                                value={pullModelName}
                                onChange={(e) => setPullModelName(e.target.value)}
                            />
                            <Button
                                onClick={() => pullOllamaModelMutation.mutate()}
                                disabled={!pullModelName || pullOllamaModelMutation.isPending}
                            >
                                {pullOllamaModelMutation.isPending ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Pulling...
                                    </>
                                ) : "Pull"}
                            </Button>
                        </div>
                        <p className="text-xs text-muted-foreground">
                            Please check your server logs/Ollama console if the pull takes a long time.
                            Ensure the container has internet access.
                        </p>
                    </div>
                )}

                <div className="grid gap-2 pt-4 border-t">
                    <Label className="flex items-center justify-between">
                        {t('settings.ai.systemPrompt', 'System Prompt')}
                        <span className="text-xs text-muted-foreground font-normal">
                            Available: {"${user.username}"}, {"${currentDate...}"}, {"${context}"}
                        </span>
                    </Label>
                    <Textarea
                        className="font-mono text-sm min-h-[300px]"
                        value={systemPrompt}
                        onChange={(e) => setSystemPrompt(e.target.value)}
                        placeholder="You are TaskFlow AI..."
                    />
                </div>

            </CardContent>
            <CardFooter>
                <Button onClick={handleSave} disabled={mutation.isPending}>
                    {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Save Settings
                </Button>
            </CardFooter>
        </Card>
    );
}
