"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Loader2, Sparkles, Trash2, Send, Bot, User } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input, Label, Select } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

export default function AiPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [configured, setConfigured] = useState(false);
  const [provider, setProviderState] = useState("openai");
  const [model, setModel] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/settings/ai");
    const j = await res.json().catch(() => ({}));
    if (res.ok) {
      setConfigured(j.configured ?? false);
      setProviderState(j.provider ?? "openai");
      setModel(j.model ?? null);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function save(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    setSaving(true);
    const data: Record<string, string> = {};
    for (const [k, v] of new FormData(form).entries()) data[k] = String(v);
    data.provider = provider;
    const res = await fetch("/api/settings/ai", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) return toast.error(j.error ?? "Save failed.");
    toast.success("AI settings saved.");
    form.reset();
    load();
  }

  async function removeConf() {
    if (!confirm("Remove the AI configuration?")) return;
    const res = await fetch("/api/settings/ai", { method: "DELETE" });
    if (!res.ok) return toast.error("Failed to remove AI config.");
    toast.success("AI config removed.");
    load();
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      <Card>
        <CardHeader>
          <CardTitle>AI reply assistant</CardTitle>
        </CardHeader>
        <CardBody>
          {loading ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" /> Loading…
            </div>
          ) : configured ? (
            <div className="flex items-center gap-3 rounded-lg bg-muted px-4 py-3">
              <Sparkles className="h-5 w-5 text-indigo-500" />
              <div className="flex-1 text-sm">
                <span className="font-medium text-foreground">Configured</span>
                <span className="ml-2 text-muted-foreground">
                  {provider} · {model ?? "default model"}
                </span>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={async () => {
                  toast.loading("Testing connection...", { id: "test-ai" });
                  try {
                    const res = await fetch("/api/settings/ai/playground", {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ history: [{ direction: "INBOUND", body: "Hello" }] }),
                    });
                    const data = await res.json().catch(() => ({}));
                    if (!res.ok) throw new Error(data.error || "Connection failed");
                    toast.success("Connection successful!", { id: "test-ai" });
                  } catch (err: any) {
                    toast.error(err.message || "Connection failed. Check your API key.", { id: "test-ai" });
                  }
                }}>
                  Test
                </Button>
                <Button variant="outline" size="sm" onClick={removeConf}>
                  <Trash2 className="h-3.5 w-3.5" /> Remove
                </Button>
              </div>
            </div>
          ) : (
            <div className="mb-4 flex items-center gap-3 rounded-lg bg-muted px-4 py-3">
              <Sparkles className="h-5 w-5 text-indigo-500" />
              <span className="text-sm font-medium text-foreground">Not configured</span>
              <span className="text-sm text-muted-foreground">Drafts and auto-replies are disabled.</span>
            </div>
          )}

          <form onSubmit={save} className="space-y-4">
            <div>
              <Label>Provider</Label>
              <Select value={provider} onChange={(e) => setProviderState(e.target.value)}>
                <option value="openai">OpenAI</option>
                <option value="anthropic">Anthropic</option>
              </Select>
            </div>
            <div>
              <Label>API key</Label>
              <Input name="apiKey" type="password" placeholder="sk-…" required />
            </div>
            <div>
              <Label>Model (optional)</Label>
              <Input
                name="model"
                placeholder={provider === "openai" ? "gpt-4o-mini" : "claude-3-5-haiku-latest"}
              />
            </div>
            <div className="flex justify-end">
              <Button type="submit" loading={saving}>
                Save
              </Button>
            </div>
          </form>
        </CardBody>
      </Card>

      {/* Playground Card */}
      <Card className="flex flex-col h-[500px]">
        <CardHeader className="pb-3 border-b">
          <CardTitle className="text-lg">AI Playground</CardTitle>
          <p className="text-sm text-muted-foreground">Test your AI assistant configuration.</p>
        </CardHeader>
        <AiPlayground configured={configured} />
      </Card>
    </div>
  );
}

function AiPlayground({ configured }: { configured: boolean }) {
  const [messages, setMessages] = useState<{ direction: "INBOUND" | "OUTBOUND"; body: string }[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);

  const sendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || loading || !configured) return;
    
    const newHistory: { direction: "INBOUND" | "OUTBOUND"; body: string }[] = [
      ...messages,
      { direction: "INBOUND", body: input }
    ];
    
    setMessages(newHistory);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch("/api/settings/ai/playground", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ history: newHistory }),
      });
      const data = await res.json();
      
      if (!res.ok) {
        toast.error(data.error ?? "Failed to get AI reply.");
      } else {
        setMessages((prev) => [...prev, { direction: "OUTBOUND", body: data.reply }]);
        if (data.knowledgeUsed) {
           toast.success("Knowledge base used for context.");
        }
      }
    } catch (err) {
      toast.error("Something went wrong.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col flex-1 overflow-hidden">
      <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-muted/50">
        {messages.length === 0 ? (
          <div className="flex h-full items-center justify-center text-center text-sm text-muted-foreground">
            Send a message to start testing.<br />(Make sure AI is configured)
          </div>
        ) : (
          messages.map((msg, i) => (
            <div key={i} className={`flex gap-3 ${msg.direction === "INBOUND" ? "justify-end" : "justify-start"}`}>
              {msg.direction === "OUTBOUND" && (
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-indigo-600">
                  <Bot className="h-4 w-4" />
                </div>
              )}
              <div className={`rounded-xl px-4 py-2 max-w-[85%] text-sm ${msg.direction === "INBOUND" ? "bg-indigo-600 text-white" : "bg-card border text-foreground"}`}>
                {msg.body}
              </div>
            </div>
          ))
        )}
        {loading && (
          <div className="flex gap-3 justify-start animate-pulse">
             <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-indigo-600">
                <Bot className="h-4 w-4" />
             </div>
             <div className="rounded-xl px-4 py-2 bg-card border text-muted-foreground text-sm">
                Thinking...
             </div>
          </div>
        )}
      </div>
      <div className="p-3 border-t bg-card">
        <form onSubmit={sendMessage} className="flex gap-2">
          <Input 
            value={input} 
            onChange={(e) => setInput(e.target.value)} 
            placeholder="Type a message..." 
            disabled={!configured || loading}
            className="flex-1"
          />
          <Button type="submit" size="icon" disabled={!configured || loading || !input.trim()}>
            <Send className="h-4 w-4" />
          </Button>
        </form>
      </div>
    </div>
  );
}
