"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { Badge, Button, Card, Select, Textarea } from "@/components/ui/Primitives";
import { chatOverWorkspace, listWorkspaceSummaries } from "@/lib/notes-client";
import type { WorkspaceSummary } from "@/lib/types";
import { toast } from "@/lib/toast";

export default function ChatPage() {
  const [workspaces, setWorkspaces] = useState<WorkspaceSummary[]>([]);
  const [workspaceId, setWorkspaceId] = useState("");
  const [message, setMessage] = useState("");
  const [answer, setAnswer] = useState<string | null>(null);
  const [citations, setCitations] = useState<Array<{ noteId: string; title: string; snippet: string }>>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    void listWorkspaceSummaries().then((w) => {
      setWorkspaces(w);
      setWorkspaceId((id) => id || w[0]?.id || "");
    });
  }, []);

  async function handleAsk() {
    if (!workspaceId.trim() || !message.trim()) return;
    setLoading(true);
    setAnswer(null);
    setCitations([]);
    try {
      const res = await chatOverWorkspace(workspaceId, message.trim());
      setAnswer(res.answer);
      setCitations(res.citations);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Chat failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <AppShell
      title="Workspace chat"
      description="Retrieval over your notes (citations below). This is not a general-purpose LLM — answers are assembled from indexed note text."
      actions={<Badge>Feature-flagged on backend (chat.rag_enabled)</Badge>}
    >
      <Card style={{ padding: "var(--nl-space-6)", display: "grid", gap: "var(--nl-space-4)", maxWidth: 720 }}>
        <label style={{ display: "grid", gap: 8 }}>
          <span style={{ fontWeight: 600 }}>Workspace</span>
          {workspaces.length === 0 ? (
            <p style={{ margin: 0, color: "var(--nl-text-secondary)", fontSize: "var(--nl-fs-sm)" }}>
              Create a workspace first (Dashboard seed or Workspaces), then return here.
            </p>
          ) : (
            <Select
              value={workspaceId}
              onChange={(e) => setWorkspaceId(e.target.value)}
              options={workspaces.map((w) => ({ value: w.id, label: w.name }))}
            />
          )}
        </label>
        <label style={{ display: "grid", gap: 8 }}>
          <span style={{ fontWeight: 600 }}>Question</span>
          <Textarea
            rows={4}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder="What did we decide about launch?"
          />
        </label>
        <Button
          type="button"
          disabled={loading || !workspaceId.trim() || workspaces.length === 0}
          loading={loading}
          onClick={() => void handleAsk()}
        >
          Ask
        </Button>
        {answer ? (
          <div style={{ display: "grid", gap: "var(--nl-space-3)" }}>
            <strong>Answer</strong>
            <div style={{ whiteSpace: "pre-wrap", lineHeight: 1.6 }}>{answer}</div>
            {citations.length ? (
              <div style={{ display: "grid", gap: "var(--nl-space-2)" }}>
                <strong>Citations</strong>
                <ul style={{ margin: 0, paddingLeft: 20 }}>
                  {citations.map((c) => (
                    <li key={c.noteId} style={{ marginBottom: 8 }}>
                      <Link href={`/notes/${c.noteId}`}>{c.title}</Link>
                      <div style={{ color: "var(--nl-text-secondary)", fontSize: "var(--nl-fs-sm)" }}>{c.snippet}</div>
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}
          </div>
        ) : null}
      </Card>
    </AppShell>
  );
}
