"use client";

import * as React from "react";
import { toast } from "sonner";
import { Loader2, Save, Brain, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const AI_PROVIDERS = [
  {
    value: "gateway",
    label: "Vercel AI Gateway",
    defaultModel: "openai/gpt-4o-mini",
    hint: "openai/gpt-4o-mini, google/gemini-2.5-flash, anthropic/claude-sonnet-4-20250514",
  },
  {
    value: "ollama",
    label: "Ollama (Local)",
    defaultModel: "llava:7b",
    hint: "llava:7b, moondream, llama3.2-vision",
  },
] as const;

export default function AiSettingsPage() {
  const [aiProvider, setAiProvider] = React.useState("gateway");
  const [aiModel, setAiModel] = React.useState("");
  const [ollamaUrl, setOllamaUrl] = React.useState("");
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [testStatus, setTestStatus] = React.useState<
    "idle" | "testing" | "success" | "error"
  >("idle");

  React.useEffect(() => {
    fetch("/api/settings")
      .then((r) => r.json())
      .then((data) => {
        setAiProvider(data.aiProvider || "gateway");
        setAiModel(data.aiModel || "");
        setOllamaUrl(data.ollamaUrl || "");
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ aiProvider, aiModel, ollamaUrl }),
      });
      if (!res.ok) throw new Error();
      toast.success("AI settings saved");
    } catch {
      toast.error("Failed to save settings");
    } finally {
      setSaving(false);
    }
  };

  const testConnection = async () => {
    setTestStatus("testing");
    try {
      const res = await fetch("/api/ai-test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ provider: aiProvider, model: aiModel, ollamaUrl }),
        signal: AbortSignal.timeout(15000),
      });
      if (res.ok) {
        setTestStatus("success");
        toast.success("AI provider connected");
      } else {
        setTestStatus("error");
        const data = await res.json().catch(() => ({}));
        toast.error(data.error || "Test failed");
      }
    } catch {
      setTestStatus("error");
      toast.error("Cannot reach AI provider");
    }
  };

  const handleProviderChange = (value: string) => {
    setAiProvider(value);
    const provider = AI_PROVIDERS.find((p) => p.value === value);
    if (provider) setAiModel(provider.defaultModel);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const currentProvider = AI_PROVIDERS.find((p) => p.value === aiProvider);

  return (
    <div className="space-y-6">
      <Card className="glass-card">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Brain className="size-4" />
            AI Provider Configuration
          </CardTitle>
          <CardDescription>
            Choose the AI service that processes your scanned response cards.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Provider</Label>
            <Select value={aiProvider} onValueChange={(v) => v && handleProviderChange(v)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {AI_PROVIDERS.map((p) => (
                  <SelectItem key={p.value} value={p.value}>
                    {p.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>Model</Label>
            <Input
              value={aiModel}
              onChange={(e) => setAiModel(e.target.value)}
              placeholder={currentProvider?.defaultModel}
            />
            {currentProvider && (
              <p className="text-xs text-muted-foreground">
                Options: {currentProvider.hint}
              </p>
            )}
          </div>

          {aiProvider === "ollama" && (
            <div className="space-y-2">
              <Label>Ollama URL</Label>
              <Input
                value={ollamaUrl}
                onChange={(e) => setOllamaUrl(e.target.value)}
                placeholder="http://192.168.68.108:11434"
              />
            </div>
          )}

          <Button variant="outline" size="sm" onClick={testConnection}>
            {testStatus === "testing" ? (
              <Loader2 className="mr-1.5 size-3.5 animate-spin" />
            ) : testStatus === "success" ? (
              <Check className="mr-1.5 size-3.5 text-emerald-500" />
            ) : (
              <Brain className="mr-1.5 size-3.5" />
            )}
            Test Connection
          </Button>
        </CardContent>
      </Card>

      <div className="flex justify-end">
        <Button onClick={handleSave} disabled={saving}>
          {saving ? (
            <Loader2 className="mr-2 size-4 animate-spin" />
          ) : (
            <Save className="mr-2 size-4" />
          )}
          Save Changes
        </Button>
      </div>
    </div>
  );
}
