"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api";
import type { OllamaModelInfo } from "@/lib/ollama";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ArrowUp, Sparkles, PanelLeft, Settings as SettingsIcon, Loader2, Brain, Wrench } from "lucide-react";
import Link from "next/link";
import { useUIStore } from "@/lib/stores/ui-store";
import { ThemeToggle } from "@/components/theme-toggle";
import { toast } from "sonner";

interface MeResponse {
  user: {
    id: string;
    username: string;
    role: string;
    ollamaUrl: string;
    defaultModel: string | null;
    defaultContext: number;
    defaultSystemPrompt: string;
    showThinking: boolean;
  };
}

interface ModelsResponse {
  models: OllamaModelInfo[];
}

export default function NewChatPage() {
  const router = useRouter();
  const toggleSidebar = useUIStore((s) => s.toggleSidebar);
  const [model, setModel] = React.useState<string>("");
  const [draft, setDraft] = React.useState("");
  const textareaRef = React.useRef<HTMLTextAreaElement>(null);

  const meQuery = useQuery({
    queryKey: ["me"],
    queryFn: () => apiFetch<MeResponse>("/api/me"),
  });
  const modelsQuery = useQuery({
    queryKey: ["models"],
    queryFn: () => apiFetch<ModelsResponse>("/api/models"),
    retry: false,
  });

  const showQuery = useQuery({
    queryKey: ["model-show", model],
    queryFn: () =>
      apiFetch<{ capabilities: string[]; supportsThinking: boolean; supportsTools: boolean }>(
        `/api/models/show?name=${encodeURIComponent(model)}`,
      ),
    enabled: !!model,
    staleTime: Infinity,
    retry: false,
  });
  const canThink = !!showQuery.data?.supportsThinking;
  const canTools = !!showQuery.data?.supportsTools;

  React.useEffect(() => {
    if (!model) {
      const def = meQuery.data?.user.defaultModel;
      const first = modelsQuery.data?.models?.[0]?.name;
      if (def && modelsQuery.data?.models.some((m) => m.name === def)) setModel(def);
      else if (first) setModel(first);
    }
  }, [meQuery.data, modelsQuery.data, model]);

  const createChat = useMutation({
    mutationFn: async (input: { firstMessage: string; model: string }) => {
      const { chat } = await apiFetch<{ chat: { id: string } }>("/api/chats", {
        method: "POST",
        body: JSON.stringify({ model: input.model }),
      });
      // Stash the first message in sessionStorage so the chat page can send it.
      try {
        sessionStorage.setItem(`pending-message:${chat.id}`, input.firstMessage);
      } catch {
        /* ignore */
      }
      return chat;
    },
    onSuccess: (chat) => {
      router.push(`/chat/${chat.id}`);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  async function handleSend() {
    const text = draft.trim();
    if (!text) return;
    if (!model) {
      toast.error("Pick a model first. Pull one in Settings → Models.");
      return;
    }
    createChat.mutate({ firstMessage: text, model });
  }

  function onKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  }

  const models = modelsQuery.data?.models ?? [];
  const ollamaOffline = modelsQuery.isError;

  return (
    <div className="flex h-full flex-col">
      <header className="flex h-14 items-center justify-between border-b border-border px-4">
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="icon-sm" onClick={toggleSidebar} aria-label="Toggle sidebar">
            <PanelLeft />
          </Button>
          <span className="font-serif text-lg">New chat</span>
        </div>
        <div className="flex items-center gap-1">
          <ThemeToggle />
          <Button asChild variant="ghost" size="icon-sm" aria-label="Settings">
            <Link href="/settings">
              <SettingsIcon />
            </Link>
          </Button>
        </div>
      </header>

      <div className="flex flex-1 flex-col items-center justify-center px-6">
        <div className="w-full max-w-2xl">
          <div className="mb-8 text-center">
            <Sparkles className="mx-auto mb-3 h-7 w-7 text-primary" />
            <h1 className="font-serif text-4xl font-medium tracking-tight">
              What can I help you with?
            </h1>
            <p className="mt-2 text-sm text-muted-foreground">
              Powered by your local Ollama runtime
            </p>
          </div>

          <div className="rounded-2xl border border-border bg-card shadow-sm focus-within:ring-2 focus-within:ring-ring/40">
            <Textarea
              ref={textareaRef}
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={onKeyDown}
              placeholder={ollamaOffline ? "Ollama appears offline — check Settings → Models" : "Message your model..."}
              className="min-h-[100px] resize-none border-0 bg-transparent p-4 text-base shadow-none focus-visible:ring-0"
              autoFocus
            />
            <div className="flex items-center justify-between p-2 pt-0">
              <div className="flex items-center gap-2 pl-2">
                <Select value={model} onValueChange={setModel}>
                  <SelectTrigger className="h-8 w-auto min-w-[160px] border-0 bg-transparent text-xs hover:bg-accent">
                    <SelectValue placeholder={models.length ? "Select a model" : "No models installed"} />
                  </SelectTrigger>
                  <SelectContent>
                    {models.map((m) => (
                      <SelectItem key={m.name} value={m.name}>
                        {m.name}
                      </SelectItem>
                    ))}
                    {models.length === 0 && (
                      <div className="px-2 py-1.5 text-xs text-muted-foreground">
                        No models. Visit Settings → Models.
                      </div>
                    )}
                  </SelectContent>
                </Select>
                {canThink && (
                  <span className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary">
                    <Brain className="h-2.5 w-2.5" />
                    thinks
                  </span>
                )}
                {canTools && (
                  <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">
                    <Wrench className="h-2.5 w-2.5" />
                    tools
                  </span>
                )}
              </div>
              <Button
                size="icon"
                onClick={handleSend}
                disabled={!draft.trim() || !model || createChat.isPending}
                className="rounded-full"
                aria-label="Send"
              >
                {createChat.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
              </Button>
            </div>
          </div>

          {ollamaOffline && (
            <p className="mt-4 text-center text-xs text-destructive">
              Could not reach Ollama. Make sure it&apos;s running and check the URL in Settings.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
