import { useState, useEffect } from 'react';
import axios from 'axios';
import { API_BASE_URL } from "@/lib/api";
import { Save, Settings, Key, Cpu, RefreshCw, Globe, Server, User, Trash, Plus } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { DEFAULT_MODEL_BY_PROVIDER, getAdditionalModels, getInitialModelForProvider, getModelProvider, getRecommendedModels, PROVIDER_LABELS, type LlmModelOption } from "@/lib/llm-models";
import { type ConfigApiResponse, type ConfigSecretsMap, getSecretInfo, getSecretPlaceholder } from "@/lib/config-secrets";

interface ConfigState {
    LLM_MODEL?: string;
    ALLOWED_PATHS?: string[];
    AUTONOMOUS_MODE?: string;
    MAX_ITERATIONS?: string;
    WEB_PORT?: string;
    LLM_PROXY_URL?: string;
    BROWSER_MODE?: string;
    BROWSER_CHANNEL?: string;
    BROWSER_CDP_URL?: string;
    BROWSER_USER_DATA_DIR?: string;
    BROWSER_PROFILE_DIRECTORY?: string;
    [key: string]: any;
}

type SecretDrafts = Record<string, string>;

const SECRET_KEYS = [
    "APP_API_KEY",
    "GEMINI_API_KEY",
    "OPENAI_API_KEY",
    "OPENROUTER_API_KEY",
    "ANTHROPIC_API_KEY",
    "XAI_API_KEY",
    "DEEPSEEK_API_KEY",
    "NVIDIA_API_KEY",
    "DASHSCOPE_API_KEY",
] as const;

const DEFAULT_CUSTOM_MODEL = "ollama/llama3";


export function ConfigPage() {
    const [config, setConfig] = useState<ConfigState>({});
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [status, setStatus] = useState<{ type: 'success' | 'error', message: string } | null>(null);
    const [secretMeta, setSecretMeta] = useState<ConfigSecretsMap>({});
    const [secretDrafts, setSecretDrafts] = useState<SecretDrafts>({});
    const [clearedSecrets, setClearedSecrets] = useState<string[]>([]);

    const [availableModels, setAvailableModels] = useState<LlmModelOption[]>([]);
    const [modelsLoading, setModelsLoading] = useState(false);
    const [showAllModels, setShowAllModels] = useState(false);

    useEffect(() => {
        fetchConfig();
        fetchModels();
    }, []);

    const fetchModels = async () => {
        try {
            setModelsLoading(true);
            const res = await axios.get(`${API_BASE_URL}/api/llm/models`);
            if (res.data.models) setAvailableModels(res.data.models);
        } catch (err) {
            console.error("Failed to load models:", err);
        } finally {
            setModelsLoading(false);
        }
    };

    const getFilteredModels = () => {
        if (!config) return [];
        return availableModels.filter(model => {
            if (model.provider === 'gemini') return !!secretDrafts.GEMINI_API_KEY || getSecretInfo(secretMeta, 'GEMINI_API_KEY').configured;
            if (model.provider === 'openai') return !!secretDrafts.OPENAI_API_KEY || getSecretInfo(secretMeta, 'OPENAI_API_KEY').configured;
            if (model.provider === 'openrouter') return !!secretDrafts.OPENROUTER_API_KEY || getSecretInfo(secretMeta, 'OPENROUTER_API_KEY').configured;
            if (model.provider === 'anthropic') return !!secretDrafts.ANTHROPIC_API_KEY || getSecretInfo(secretMeta, 'ANTHROPIC_API_KEY').configured;
            if (model.provider === 'xai') return !!secretDrafts.XAI_API_KEY || getSecretInfo(secretMeta, 'XAI_API_KEY').configured;
            if (model.provider === 'deepseek') return !!secretDrafts.DEEPSEEK_API_KEY || getSecretInfo(secretMeta, 'DEEPSEEK_API_KEY').configured;
            if (model.provider === 'nvidia') return !!secretDrafts.NVIDIA_API_KEY || getSecretInfo(secretMeta, 'NVIDIA_API_KEY').configured;
            if (model.provider === 'qwen') return !!secretDrafts.DASHSCOPE_API_KEY || getSecretInfo(secretMeta, 'DASHSCOPE_API_KEY').configured;
            return true;
        });
    };

    const fetchConfig = async () => {
        setLoading(true);
        // ... existing fetchConfig logic ...
        try {
            const res = await axios.get<ConfigApiResponse<ConfigState>>(`${API_BASE_URL}/api/config`);
            const nextEnv = res.data.env || {};
            setConfig(nextEnv);
            setSecretMeta(res.data.secrets || {});
            setSecretDrafts({});
            setClearedSecrets([]);
        } catch (err) {
            console.error("Failed to load settings:", err);
            setStatus({ type: 'error', message: "Failed to load configuration." });
        } finally {
            setLoading(false);
        }
    };


    // ... existing handleSave ...

    const handleSave = async () => {
        setSaving(true);
        setStatus(null);

        const normalizedModel = String(config.LLM_MODEL || "").trim() || DEFAULT_CUSTOM_MODEL;

        try {
            const secretUpdates = Object.fromEntries(
                Object.entries(secretDrafts).filter(([, value]) => value.trim() !== "")
            );
            const res = await axios.post(`${API_BASE_URL}/api/config`, {
                env: {
                    ...config,
                    LLM_MODEL: normalizedModel,
                    ...secretUpdates,
                },
                clear_secrets: clearedSecrets,
            });
            if (res.data.error) throw new Error(res.data.error);
            if (secretDrafts.APP_API_KEY?.trim()) {
                localStorage.setItem("limebot_api_key", secretDrafts.APP_API_KEY.trim());
                axios.defaults.headers.common["X-API-Key"] = secretDrafts.APP_API_KEY.trim();
            }
            setSecretMeta((prev) => {
                const next = { ...prev };
                for (const key of SECRET_KEYS) {
                    if (clearedSecrets.includes(key)) {
                        next[key] = { configured: false, masked: "", last4: "" };
                    } else if (secretDrafts[key]?.trim()) {
                        const val = secretDrafts[key].trim();
                        next[key] = {
                            configured: true,
                            masked: `••••${val.slice(-4)}`,
                            last4: val.slice(-4),
                        };
                    }
                }
                return next;
            });
            setSecretDrafts({});
            setClearedSecrets([]);
            setStatus({ type: 'success', message: "Configuration saved!" });
        } catch (err) {
            console.error("Failed to save config:", err);
            setStatus({ type: 'error', message: "Failed to save configuration." });
        } finally {
            setSaving(false);
        }
    };

    const handleChange = (key: string, value: any) => {
        setConfig(prev => ({ ...prev, [key]: value }));
    };

    const handleSecretChange = (key: string, value: string) => {
        setSecretDrafts(prev => ({ ...prev, [key]: value }));
        setClearedSecrets(prev => prev.filter((item) => item !== key));
    };

    const markSecretForClear = (key: string) => {
        setSecretDrafts(prev => ({ ...prev, [key]: "" }));
        setClearedSecrets(prev => prev.includes(key) ? prev : [...prev, key]);
    };

    const renderSecretInput = (key: typeof SECRET_KEYS[number], label: string, placeholder: string) => {
        const info = getSecretInfo(secretMeta, key);
        const isCleared = clearedSecrets.includes(key);
        return (
            <div className="grid gap-2">
                <div className="flex items-center justify-between gap-2">
                    <Label htmlFor={key.toLowerCase()}>{label}</Label>
                    <span className="text-[10px] text-muted-foreground">
                        {isCleared ? 'Will be cleared' : info.configured ? `Stored ${info.masked}` : 'Not configured'}
                    </span>
                </div>
                <div className="flex gap-2">
                    <Input
                        id={key.toLowerCase()}
                        type="password"
                        value={secretDrafts[key] || ""}
                        onChange={(e) => handleSecretChange(key, e.target.value)}
                        placeholder={getSecretPlaceholder(secretMeta, key, placeholder)}
                    />
                    <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        onClick={() => markSecretForClear(key)}
                        title={`Clear ${label}`}
                    >
                        <Trash className="h-4 w-4" />
                    </Button>
                </div>
            </div>
        );
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-full">
                <RefreshCw className="w-8 h-8 animate-spin text-primary" />
            </div>
        );
    }

    const filteredModels = getFilteredModels();
    const knownModel = filteredModels.find((model) => model.id === config.LLM_MODEL);
    const selectedProvider = knownModel?.provider || getModelProvider(config.LLM_MODEL);
    const providerOptions = Object.keys(PROVIDER_LABELS).filter((provider) => provider !== "custom");
    const recommendedModels = selectedProvider === 'custom'
        ? []
        : getRecommendedModels(filteredModels, selectedProvider);
    const additionalModels = selectedProvider === 'custom'
        ? []
        : getAdditionalModels(filteredModels, selectedProvider);
    const selectedHiddenModel = additionalModels.find((model) => model.id === config.LLM_MODEL);
    const recommendedDisplayModels = selectedHiddenModel
        ? [selectedHiddenModel, ...recommendedModels]
        : recommendedModels;
    const additionalDisplayModels = selectedHiddenModel
        ? additionalModels.filter((model) => model.id !== selectedHiddenModel.id)
        : additionalModels;

    return (
        <div className="h-full overflow-y-auto p-6 md:p-8 bg-background/50">
            <div className="max-w-4xl mx-auto space-y-8">
                <header className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold flex items-center gap-2">
                            <Settings className="h-6 w-6 text-primary" />
                            Configuration
                        </h1>
                        <p className="text-muted-foreground mt-1">
                            Manage your bot's environment variables and model settings.
                        </p>
                    </div>
                    <Button onClick={handleSave} disabled={saving} className="bg-primary hover:bg-primary/90 text-primary-foreground font-bold">
                        {saving ? (
                            <>Saving...</>
                        ) : (
                            <>
                                <Save className="mr-2 h-4 w-4" /> Save Changes
                            </>
                        )}
                    </Button>
                </header>

                {status && (
                    <Alert className={status.type === 'success' ? "border-primary/50 bg-primary/10 text-primary" : "border-destructive/50 bg-destructive/10 text-destructive"}>
                        {status.type === 'success' ? <RefreshCw className="h-4 w-4" /> : <Settings className="h-4 w-4" />}
                        <AlertTitle>{status.type === 'success' ? "Saved" : "Error"}</AlertTitle>
                        <AlertDescription>{status.message}</AlertDescription>
                    </Alert>
                )}

                <Tabs defaultValue="general" className="w-full">
                    <TabsList className="grid w-full grid-cols-3 max-w-[400px]">
                        <TabsTrigger value="general">General</TabsTrigger>
                        <TabsTrigger value="credentials">Credentials</TabsTrigger>
                        <TabsTrigger value="system">System</TabsTrigger>
                    </TabsList>

                    {/* GENERAL SETTINGS */}
                    <TabsContent value="general" className="space-y-4 mt-6">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Cpu className="h-5 w-5" />
                                    Model Settings
                                </CardTitle>
                                <CardDescription>Select and configure the AI model.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="provider">Provider</Label>
                                    <Select
                                        value={selectedProvider}
                                        onValueChange={(value) => {
                                            setShowAllModels(false);
                                            if (value === "custom") {
                                                handleChange("LLM_MODEL", config.LLM_MODEL?.trim() || DEFAULT_CUSTOM_MODEL);
                                                return;
                                            }
                                            handleChange(
                                                "LLM_MODEL",
                                                getInitialModelForProvider(filteredModels, value) || DEFAULT_MODEL_BY_PROVIDER[value],
                                            );
                                        }}
                                    >
                                        <SelectTrigger id="provider">
                                            <SelectValue placeholder="Select Provider" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {providerOptions.map((provider) => (
                                                <SelectItem key={provider} value={provider}>
                                                    {PROVIDER_LABELS[provider] || provider}
                                                </SelectItem>
                                            ))}
                                            <SelectSeparator />
                                            <SelectItem value="custom">{PROVIDER_LABELS.custom}</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <p className="text-[10px] text-muted-foreground">
                                        Start with a short recommended list per provider. Expand only when you need niche or experimental models.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="model">LLM Model</Label>
                                    <div className="flex gap-2">
                                        <Select
                                            disabled={modelsLoading}
                                            value={
                                                modelsLoading
                                                    ? "loading"
                                                    : selectedProvider === "custom"
                                                        ? "custom"
                                                        : filteredModels.find(m => m.id === config.LLM_MODEL)
                                                        ? config.LLM_MODEL
                                                        : "custom"
                                            }
                                            onValueChange={(val) => {
                                                if (val === "loading") return;
                                                if (val === "custom") {
                                                    const isCurrentlyKnown = filteredModels.find(m => m.id === config.LLM_MODEL);
                                                    if (isCurrentlyKnown) {
                                                        handleChange("LLM_MODEL", "");
                                                    }
                                                } else {
                                                    handleChange("LLM_MODEL", val);
                                                }
                                            }}
                                        >
                                            <SelectTrigger id="model" className="flex-1">
                                                <SelectValue placeholder={modelsLoading ? "Scanning Models..." : "Select Model"} />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {modelsLoading ? (
                                                    <SelectItem value="loading" disabled className="text-muted-foreground flex items-center gap-2">
                                                        <RefreshCw className="h-3 w-3 animate-spin" /> Scanning Models...
                                                    </SelectItem>
                                                ) : (
                                                    <>
                                                        <SelectItem value="custom" className="font-semibold text-primary">
                                                            Custom / Local Model
                                                        </SelectItem>
                                                        {recommendedDisplayModels.length > 0 && (
                                                            <>
                                                                <SelectSeparator />
                                                                <SelectGroup>
                                                                    <SelectLabel>Recommended</SelectLabel>
                                                                    {recommendedDisplayModels.map((model) => (
                                                                        <SelectItem key={model.id} value={model.id}>
                                                                            {model.name}
                                                                        </SelectItem>
                                                                    ))}
                                                                </SelectGroup>
                                                            </>
                                                        )}
                                                        {showAllModels && additionalDisplayModels.length > 0 && (
                                                            <>
                                                                <SelectSeparator />
                                                                <SelectGroup>
                                                                    <SelectLabel>All {PROVIDER_LABELS[selectedProvider] || selectedProvider} Models</SelectLabel>
                                                                    {additionalDisplayModels.map((model) => (
                                                                        <SelectItem key={model.id} value={model.id}>
                                                                            {model.name}
                                                                        </SelectItem>
                                                                    ))}
                                                                </SelectGroup>
                                                            </>
                                                        )}
                                                    </>
                                                )}
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    {selectedProvider !== 'custom' && additionalDisplayModels.length > 0 && (
                                        <div className="flex items-center justify-between text-xs text-muted-foreground">
                                            <span>
                                                Showing {recommendedDisplayModels.length} recommended model{recommendedDisplayModels.length === 1 ? '' : 's'} first.
                                            </span>
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                size="sm"
                                                className="h-7 px-2 text-xs"
                                                onClick={() => setShowAllModels((prev) => !prev)}
                                            >
                                                {showAllModels
                                                    ? 'Show recommended only'
                                                    : `Show all ${recommendedDisplayModels.length + additionalDisplayModels.length} models`}
                                            </Button>
                                        </div>
                                    )}

                                    {(selectedProvider === "custom" || !filteredModels.find(m => m.id === config.LLM_MODEL) || config.LLM_MODEL?.startsWith("ollama/")) && (
                                        <div className="pt-2 animate-in fade-in slide-in-from-top-2">
                                            <Label htmlFor="custom_model" className="text-xs text-muted-foreground">Custom Model Name (e.g. ollama/llama3)</Label>
                                            <Input
                                                id="custom_model"
                                                value={config.LLM_MODEL || ""}
                                                onChange={(e) => handleChange("LLM_MODEL", e.target.value)}
                                                placeholder="provider/model-name"
                                                className="mt-1"
                                            />
                                        </div>
                                    )}
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="base_url">LLM Base URL (Optional)</Label>
                                    <Input
                                        id="base_url"
                                        value={config.LLM_BASE_URL || ""}
                                        onChange={(e) => handleChange("LLM_BASE_URL", e.target.value)}
                                        placeholder="e.g. http://localhost:11434"
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Required for local models (Ollama, LocalAI). Defaults to empty for cloud providers.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="llm_proxy_url">LLM Proxy / Gateway URL (Middleware)</Label>
                                    <Input
                                        id="llm_proxy_url"
                                        placeholder="http://localhost:8080/v1 (e.g., Open Guardian, AI Gateway)"
                                        value={config.LLM_PROXY_URL || ""}
                                        onChange={(e) => handleChange("LLM_PROXY_URL", e.target.value)}
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Routes all LLM traffic through external security or caching middleware. Overrides default provider endpoints.
                                    </p>
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <User className="h-5 w-5" />
                                    Personalization
                                </CardTitle>
                                <CardDescription>Configure how the bot interacts with users.</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="flex items-center justify-between p-4 bg-cyan-500/10 rounded-lg border border-cyan-500/20">
                                    <div className="space-y-0.5">
                                        <div className="flex items-center gap-2">
                                            <Label htmlFor="dynamic_personality">Adaptive Persona</Label>
                                            <span className="text-[10px] font-bold bg-cyan-500 text-white px-1.5 py-0.5 rounded uppercase tracking-wider">Experimental</span>
                                        </div>
                                        <p className="text-xs text-muted-foreground max-w-md">
                                            Allows the bot to learn from your conversations, adjusting its tone and relationship level dynamically based on interactions.
                                        </p>
                                    </div>
                                    <Switch
                                        id="dynamic_personality"
                                        checked={config.ENABLE_DYNAMIC_PERSONALITY === 'true'}
                                        onCheckedChange={(checked) => handleChange('ENABLE_DYNAMIC_PERSONALITY', checked ? 'true' : 'false')}
                                    />
                                </div>
                            </CardContent>
                        </Card>
                    </TabsContent>


                    {/* CREDENTIALS */}
                    <TabsContent value="credentials" className="space-y-4 mt-6">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Key className="h-5 w-5" />
                                    API Keys
                                </CardTitle>
                                <CardDescription>Manage keys for AI providers and external services.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-6">
                                <div className="grid gap-2 p-4 bg-primary/5 rounded-lg border border-primary/10">
                                    <Label htmlFor="app_api_key" className="text-foreground/90 font-semibold">LimeBot Access Key</Label>
                                    <div className="text-[10px] text-muted-foreground">
                                        {clearedSecrets.includes('APP_API_KEY')
                                            ? 'Will be cleared on save'
                                            : getSecretInfo(secretMeta, 'APP_API_KEY').configured
                                                ? `Stored ${getSecretInfo(secretMeta, 'APP_API_KEY').masked}`
                                                : 'Not configured'}
                                    </div>
                                    <div className="flex gap-2">
                                        <Input
                                            id="app_api_key"
                                            type="password"
                                            value={secretDrafts.APP_API_KEY || ""}
                                            onChange={(e) => handleSecretChange("APP_API_KEY", e.target.value)}
                                            placeholder={getSecretPlaceholder(secretMeta, 'APP_API_KEY', 'Secure Key...')}
                                            className="bg-background/50 flex-1"
                                        />
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            onClick={() => handleSecretChange("APP_API_KEY", crypto.randomUUID())}
                                            title="Regenerate Key"
                                        >
                                            <RefreshCw className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="icon"
                                            onClick={() => markSecretForClear("APP_API_KEY")}
                                            title="Clear Key"
                                        >
                                            <Trash className="h-4 w-4" />
                                        </Button>
                                    </div>
                                    <p className="text-[10px] text-muted-foreground">
                                        Used to secure the frontend connection. if changed, you must update the frontend or re-login.
                                    </p>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="grid gap-4 border p-4 rounded-lg bg-background/30">
                                        {renderSecretInput("GEMINI_API_KEY", "Google Gemini API Key", "sk-...")}
                                    </div>
                                    {renderSecretInput("OPENAI_API_KEY", "OpenAI API Key", "sk-...")}
                                    {renderSecretInput("OPENROUTER_API_KEY", "OpenRouter API Key", "sk-or-...")}
                                    {renderSecretInput("ANTHROPIC_API_KEY", "Anthropic API Key", "sk-ant-...")}
                                    {renderSecretInput("XAI_API_KEY", "xAI (Grok) API Key", "xai-...")}
                                    {renderSecretInput("DEEPSEEK_API_KEY", "DeepSeek API Key", "sk-...")}
                                    {renderSecretInput("NVIDIA_API_KEY", "NVIDIA API Key", "nvapi-...")}
                                    {renderSecretInput("DASHSCOPE_API_KEY", "Qwen (DashScope) API Key", "ds-...")}
                                </div>

                                <div className="rounded-lg border border-border/60 bg-background/30 p-4">
                                    <p className="text-sm font-medium">Channel credentials live under Channels & Presence</p>
                                    <p className="mt-1 text-[11px] text-muted-foreground">
                                        Telegram, Discord, and WhatsApp connection settings are managed in their channel tabs so tokens and enable switches stay together.
                                    </p>
                                </div>
                            </CardContent>
                        </Card>
                    </TabsContent>

                    {/* SYSTEM SETTINGS */}
                    <TabsContent value="system" className="space-y-4 mt-6">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Cpu className="h-5 w-5 text-yellow-500" />
                                    Autonomous Mode
                                </CardTitle>
                                <CardDescription className="text-yellow-500/80">
                                    DANGER: Allow the bot to execute ANY command without confirmation.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="flex items-center justify-between p-4 bg-yellow-500/10 rounded-lg border border-yellow-500/20">
                                    <div className="space-y-0.5">
                                        <Label htmlFor="autonomous_mode" className="text-yellow-500 font-bold">Enable Full Autonomy</Label>
                                        <p className="text-xs text-muted-foreground mt-1">
                                            Bypasses all confirmation prompts for tools like code execution and file writing.
                                        </p>
                                    </div>
                                    <Switch
                                        id="autonomous_mode"
                                        checked={config.AUTONOMOUS_MODE === 'true'}
                                        onCheckedChange={(checked) => handleChange('AUTONOMOUS_MODE', checked ? 'true' : 'false')}
                                    />
                                </div>
                                <div className="mt-4 grid gap-3 p-4 bg-card/50 rounded-lg border border-border/50">
                                    <div className="space-y-1">
                                        <Label htmlFor="max_iterations" className="font-semibold flex items-center gap-2">
                                            Max Tool Interactions
                                        </Label>
                                        <p className="text-xs text-muted-foreground">
                                            The maximum number of tools the bot can run autonomously in a single response before forcefully stopping. Prevents infinite loops.
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <Input
                                            id="max_iterations"
                                            type="number"
                                            min="1"
                                            max="200"
                                            value={config.MAX_ITERATIONS || "30"}
                                            onChange={(e) => handleChange("MAX_ITERATIONS", e.target.value)}
                                            className="w-24 font-mono text-center"
                                        />
                                    </div>
                                </div>
                                <div className="mt-4 grid gap-3 p-4 bg-card/50 rounded-lg border border-border/50">
                                    <div className="space-y-1">
                                        <Label htmlFor="command_timeout" className="font-semibold flex items-center gap-2">
                                            Command Timeout (Seconds)
                                        </Label>
                                        <p className="text-xs text-muted-foreground">
                                            The maximum duration a tool (like Discord Voice) can run before being forcefully stopped. Set to 0 for infinite (no timeout).
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <Input
                                            id="command_timeout"
                                            type="number"
                                            min="0"
                                            value={config.COMMAND_TIMEOUT !== undefined ? config.COMMAND_TIMEOUT : "300.0"}
                                            onChange={(e) => handleChange("COMMAND_TIMEOUT", e.target.value)}
                                            className="w-24 font-mono text-center"
                                        />
                                    </div>
                                </div>
                                <div className="mt-4 grid gap-3 p-4 bg-card/50 rounded-lg border border-border/50">
                                    <div className="space-y-1">
                                        <Label htmlFor="stall_timeout" className="font-semibold flex items-center gap-2">
                                            Stall Detection Timeout (Seconds)
                                        </Label>
                                        <p className="text-xs text-muted-foreground">
                                            If a command produces no output for this many seconds, it's assumed to be waiting for interactive input and gets killed. Set to 0 to disable stall detection.
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <Input
                                            id="stall_timeout"
                                            type="number"
                                            min="0"
                                            value={config.STALL_TIMEOUT !== undefined ? config.STALL_TIMEOUT : "30"}
                                            onChange={(e) => handleChange("STALL_TIMEOUT", e.target.value)}
                                            className="w-24 font-mono text-center"
                                        />
                                    </div>
                                </div>
                                <div className="mt-4 grid gap-3 p-4 bg-card/50 rounded-lg border border-border/50">
                                    <div className="space-y-1">
                                        <Label htmlFor="web_port" className="font-semibold flex items-center gap-2">
                                            Web Server Port
                                        </Label>
                                        <p className="text-xs text-muted-foreground">
                                            The port used by the web server and API. Changing this will require a restart.
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <Input
                                            id="web_port"
                                            type="number"
                                            min="1"
                                            max="65535"
                                            value={config.WEB_PORT || "8000"}
                                            onChange={(e) => handleChange("WEB_PORT", e.target.value)}
                                            className="w-24 font-mono text-center"
                                        />
                                    </div>
                                </div>
                                <div className="mt-4 grid gap-3 p-4 bg-card/50 rounded-lg border border-yellow-500/30">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <Label htmlFor="allow_unsafe_commands" className="font-semibold flex items-center gap-2 text-yellow-500">
                                                Allow Unsafe Commands
                                            </Label>
                                            <p className="text-xs text-muted-foreground">
                                                Allows shell operators such as redirects ({'>'}), semicolons, and pipes, and also permits privileged commands like <code className="font-mono">sudo</code>, <code className="font-mono">chmod</code>, and <code className="font-mono">chown</code>. Useful for advanced workflows, but it reduces sandboxing.
                                            </p>
                                        </div>
                                        <Switch
                                            id="allow_unsafe_commands"
                                            checked={config.ALLOW_UNSAFE_COMMANDS === 'true'}
                                            onCheckedChange={(checked) => handleChange('ALLOW_UNSAFE_COMMANDS', checked ? 'true' : 'false')}
                                        />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Globe className="h-5 w-5" />
                                    Browser Session
                                </CardTitle>
                                <CardDescription>
                                    Control whether the browser tool uses isolated LimeBot profiles, a shared LimeBot profile, your system browser profile, or a live browser session over CDP.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="browser_mode">Browser Mode</Label>
                                    <Select
                                        value={config.BROWSER_MODE || "isolated"}
                                        onValueChange={(value) => handleChange("BROWSER_MODE", value)}
                                    >
                                        <SelectTrigger id="browser_mode">
                                            <SelectValue placeholder="Select browser mode" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="isolated">isolated</SelectItem>
                                            <SelectItem value="shared">shared</SelectItem>
                                            <SelectItem value="system">system</SelectItem>
                                            <SelectItem value="attach">attach</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <p className="text-[10px] text-muted-foreground">
                                        `isolated` keeps one browser profile per chat. `shared` reuses one LimeBot profile. `system` launches against your real Chrome/Edge profile. `attach` connects to an already-running browser with remote debugging enabled.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="browser_channel">Browser Channel</Label>
                                    <Input
                                        id="browser_channel"
                                        value={config.BROWSER_CHANNEL || ""}
                                        onChange={(e) => handleChange("BROWSER_CHANNEL", e.target.value)}
                                        placeholder="chrome, msedge, or chromium"
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Optional. Recommended for `system` mode so LimeBot opens the same browser family as your real profile.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="browser_cdp_url">CDP URL</Label>
                                    <Input
                                        id="browser_cdp_url"
                                        value={config.BROWSER_CDP_URL || ""}
                                        onChange={(e) => handleChange("BROWSER_CDP_URL", e.target.value)}
                                        placeholder="http://127.0.0.1:9222"
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Used by `attach` mode. Start Chrome or Edge with `--remote-debugging-port=9222` to reuse the live logged-in session.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="browser_user_data_dir">Browser User Data Dir</Label>
                                    <Input
                                        id="browser_user_data_dir"
                                        value={config.BROWSER_USER_DATA_DIR || ""}
                                        onChange={(e) => handleChange("BROWSER_USER_DATA_DIR", e.target.value)}
                                        placeholder="C:\\Users\\you\\AppData\\Local\\Google\\Chrome\\User Data"
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Optional override for `system` mode. Leave empty to auto-detect a local Chrome/Edge/Chromium profile.
                                    </p>
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="browser_profile_directory">Profile Directory</Label>
                                    <Input
                                        id="browser_profile_directory"
                                        value={config.BROWSER_PROFILE_DIRECTORY || ""}
                                        onChange={(e) => handleChange("BROWSER_PROFILE_DIRECTORY", e.target.value)}
                                        placeholder="Default or Profile 1"
                                        className="font-mono text-sm"
                                    />
                                    <p className="text-[10px] text-muted-foreground">
                                        Optional sub-profile inside the browser user data directory. Useful when your login lives in a non-default Chrome/Edge profile.
                                    </p>
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Settings className="h-5 w-5" />
                                    Workspace Security
                                </CardTitle>
                                <CardDescription>Control file access and permissions.</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="grid gap-2">
                                    <Label htmlFor="allowed_paths">Allowed File Paths</Label>
                                    <div className="space-y-2 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
                                        {(() => {
                                            let pathsArr: string[] = [];
                                            if (Array.isArray(config.ALLOWED_PATHS)) {
                                                pathsArr = config.ALLOWED_PATHS;
                                            } else if (typeof config.ALLOWED_PATHS === "string") {
                                                pathsArr = (config.ALLOWED_PATHS as string).split(",").filter(Boolean);
                                            }

                                            return pathsArr.map((path, idx) => (
                                                <div key={idx} className="flex gap-2 isolate">
                                                    <Input
                                                        value={path}
                                                        onChange={(e) => {
                                                            const paths = [...pathsArr];
                                                            paths[idx] = e.target.value;
                                                            handleChange("ALLOWED_PATHS", paths);
                                                        }}
                                                        placeholder="Absolute path..."
                                                    />
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="text-destructive hover:bg-destructive/10 shrink-0"
                                                        onClick={() => {
                                                            const paths = [...pathsArr];
                                                            paths.splice(idx, 1);
                                                            handleChange("ALLOWED_PATHS", paths);
                                                        }}
                                                    >
                                                        <Trash className="h-4 w-4" />
                                                    </Button>
                                                </div>
                                            ));
                                        })()}
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            className="w-full flex items-center justify-center gap-2 border-dashed"
                                            onClick={() => {
                                                let pathsArr: string[] = [];
                                                if (Array.isArray(config.ALLOWED_PATHS)) {
                                                    pathsArr = [...config.ALLOWED_PATHS];
                                                } else if (typeof config.ALLOWED_PATHS === "string") {
                                                    pathsArr = (config.ALLOWED_PATHS as string).split(",").filter(Boolean);
                                                }
                                                pathsArr.push("");
                                                handleChange("ALLOWED_PATHS", pathsArr);
                                            }}
                                        >
                                            <Plus className="h-4 w-4" />
                                            Add Path
                                        </Button>
                                    </div>
                                    <p className="text-xs text-muted-foreground mt-2">
                                        Absolute paths the bot is allowed to access and edit.
                                    </p>
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Globe className="h-5 w-5" />
                                    Remote Access
                                </CardTitle>
                                <CardDescription>Network details for connecting to LimeBot.</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="bg-muted/30 p-4 rounded-lg border border-border/50">
                                    <div className="flex items-start gap-3">
                                        <Server className="h-5 w-5 text-primary mt-1" />
                                        <div className="space-y-2 flex-1">
                                            <h3 className="text-sm font-medium">Network Interfaces</h3>
                                            <div className="space-y-1">
                                                <RemoteStatus port={config.WEB_PORT || "8000"} />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    </TabsContent>
                </Tabs>
            </div>
        </div>
    );
}

function RemoteStatus({ port }: { port: string }) {
    const [status, setStatus] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        axios.get(`${API_BASE_URL}/api/setup/tailscale`)
            .then(res => setStatus(res.data))
            .catch(err => console.error("Failed to check network:", err))
            .finally(() => setLoading(false));
    }, []);

    if (loading) return <div className="text-xs text-muted-foreground animate-pulse">Scanning network...</div>;

    if (!status || status.error) {
        return <div className="text-xs text-destructive">Network check failed.</div>;
    }

    const tailscale = status.interfaces?.find((i: any) => i.is_tailscale);
    const lan = status.interfaces?.find((i: any) => !i.is_tailscale && i.ip !== '127.0.0.1');

    return (
        <div className="space-y-3">
            {tailscale ? (
                <div className="p-2 bg-emerald-500/10 border border-emerald-500/20 rounded text-sm">
                    <div className="flex items-center gap-2 text-emerald-500 font-medium mb-1">
                        <span className="relative flex h-2 w-2">
                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                            <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                        </span>
                        Tailscale Active
                    </div>
                    <div className="font-mono text-xs select-all cursor-text bg-background/50 p-1 rounded px-2">
                        http://{tailscale.ip}:{port}
                    </div>
                </div>
            ) : (
                <div className="p-2 bg-orange-500/10 border border-orange-500/20 rounded text-sm">
                    <div className="text-orange-500 font-medium text-xs mb-1">Tailscale Not Detected</div>
                    <p className="text-[10px] text-muted-foreground">
                        Install Tailscale to access this bot securely from anywhere.
                    </p>
                </div>
            )}

            {lan && (
                <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">LAN Access:</div>
                    <div className="font-mono text-xs select-all cursor-text bg-background/50 p-1 rounded px-2 inline-block">
                        http://{lan.ip}:{port}
                    </div>
                </div>
            )}
        </div>
    );
}
