"use client";

import { useState, useEffect } from "react";
import { useFamily } from "@/app/FamilyProvider";
import { Button, Input, ConfirmDialog } from "@/components/ui";
import type { AIChat, ChatSession } from "@/types";
import { fmtDate } from "@/lib/date-ist";

export default function AIChatPage() {
  const { childId } = useFamily();
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string>("");
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [error, setError] = useState<string>("");
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  useEffect(() => {
    if (childId) {
      fetchSessions();
    }
  }, [childId]);

  const fetchSessions = async () => {
    if (!childId) return;
    try {
      const res = await fetch(`/api/chat?childId=${childId}`);
      const data = await res.json();
      if (data.error) {
        setError(data.error);
        return;
      }
      const fetched = data.sessions || [];
      setSessions(fetched);
      setError("");
      if (fetched.length > 0 && !currentSessionId) {
        setCurrentSessionId(fetched[0].id);
      }
    } catch (err) {
      console.error("Failed to fetch:", err);
    }
  };

  const createNewSession = async () => {
    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ childId, title: "New conversation" }),
      });
      const data = await res.json();
      if (data.session) {
        // POST /api/chat returns a session without a `messages` field — normalize it
        // to an empty array so the render path (currentSession.messages.length) never
        // hits `undefined.length`, which crashed the page on the first new chat.
        const newSession = { ...data.session, messages: [] };
        setSessions([newSession, ...sessions]);
        setCurrentSessionId(newSession.id);
        setSidebarOpen(false);
      }
    } catch (err) {
      console.error("Failed to create:", err);
    }
  };

  const currentSession = sessions.find(s => s.id === currentSessionId);

  const handleSend = async () => {
    if (!input.trim() || loading) return;
    setLoading(true);

    const userContent = input.trim();
    setInput("");

    const tempUserMsg = { id: "temp-" + Date.now(), role: "user" as const, content: userContent, createdAt: new Date().toISOString() };
    if (currentSessionId) {
      const sessionIdx = sessions.findIndex(s => s.id === currentSessionId);
      if (sessionIdx >= 0) {
        const updatedSessions = [...sessions];
        updatedSessions[sessionIdx] = { ...updatedSessions[sessionIdx], messages: [...(updatedSessions[sessionIdx].messages || []), tempUserMsg] };
        setSessions(updatedSessions);
      }
    }

    let sessionId = currentSessionId;
    if (!sessionId && childId) {
      try {
        const res = await fetch("/api/chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ childId, title: userContent.slice(0, 30) }),
        });
        const data = await res.json();
        if (data.session) {
          sessionId = data.session.id;
          const newSession = { ...data.session, messages: [tempUserMsg] };
          setSessions([newSession, ...sessions]);
          setCurrentSessionId(sessionId);
        }
      } catch (err) {
        console.error("Failed to create session:", err);
        setLoading(false);
        return;
      }
    }

    if (!sessionId) {
      setLoading(false);
      return;
    }

    try {
      await fetch("/api/chat", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sessionId, role: "user", content: userContent }),
      });

      const aiRes = await fetch("/api/ai", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: [{ role: "user", content: userContent }] }),
      });
      const aiData = await aiRes.json();

      if (aiData.reply) {
        await fetch("/api/chat", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ sessionId, role: "assistant", content: aiData.reply }),
        });
      }

      fetchSessions();
    } catch (err) {
      console.error("Failed to send:", err);
    }
    setLoading(false);
  };

  const deleteSession = async (id: string) => {
    try {
      await fetch(`/api/chat?id=${id}`, { method: "DELETE" });
      const remaining = sessions.filter(s => s.id !== id);
      setSessions(remaining);
      setDeleteConfirm(null);
      if (currentSessionId === id) {
        setCurrentSessionId(remaining[0]?.id || "");
      }
    } catch (err) {
      console.error("Failed to delete:", err);
    }
  };

  return (
    <div className="flex h-screen pb-16 bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 overflow-hidden">

      {/* Sidebar overlay on mobile */}
      {sidebarOpen && (
        <div className="fixed inset-0 bg-black/40 z-20 md:hidden" onClick={() => setSidebarOpen(false)} />
      )}

      {/* Sidebar */}
      <div className={`
        fixed md:relative z-30 md:z-auto h-full
        ${sidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"}
        ${sidebarOpen ? "md:w-64" : "md:w-0"}
        w-64 transition-all duration-200 overflow-hidden flex-shrink-0
      `}>
        <div className="w-64 h-full flex flex-col border-r bg-white dark:bg-gray-800">
          <div className="p-4 flex justify-between items-center border-b dark:border-gray-700">
            <div className="flex items-center gap-2">
              <a href="/menu" className="text-rose-500 dark:text-rose-400">←</a>
              <h1 className="font-bold dark:text-white">Chats</h1>
            </div>
            <Button size="sm" onClick={createNewSession} className="w-8 h-8 !p-0 rounded-full">+</Button>
          </div>
          <div className="flex-1 overflow-y-auto p-2 space-y-1">
            {sessions.length === 0 ? (
              <p className="text-sm text-gray-400 dark:text-gray-500 text-center mt-8">No chats yet</p>
            ) : sessions.map(session => (
              <div
                key={session.id}
                onClick={() => { setCurrentSessionId(session.id); setSidebarOpen(false); }}
                className={`p-3 rounded-lg cursor-pointer flex justify-between items-center group transition-colors
                  ${session.id === currentSessionId
                    ? "bg-rose-100 dark:bg-rose-900/50"
                    : "hover:bg-gray-100 dark:hover:bg-gray-700"
                  }`}
              >
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium truncate dark:text-gray-100">{session.title}</div>
                  <div className="text-xs text-gray-400 dark:text-gray-500">{fmtDate(session.updatedAt)}</div>
                </div>
                <button
                  onClick={(e) => { e.stopPropagation(); setDeleteConfirm(session.id); }}
                  className="text-gray-300 dark:text-gray-600 group-hover:text-red-400 dark:group-hover:text-red-400 text-xs p-1 ml-1 flex-shrink-0 transition-colors"
                >
                  🗑️
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Main chat */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <div className="p-4 flex items-center justify-between border-b bg-white dark:bg-gray-800 flex-shrink-0">
          <div className="flex items-center gap-3">
            <button onClick={() => setSidebarOpen(!sidebarOpen)} className="text-rose-500 dark:text-rose-400 text-xl">☰</button>
            <span className="font-medium dark:text-white truncate">{currentSession?.title || "AI Chat"}</span>
          </div>
          <a href="/menu" className="text-rose-500 dark:text-rose-400 text-sm flex-shrink-0">← Home</a>
        </div>

        {error && (
          <div className="px-4 py-2 bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 text-sm flex-shrink-0">
            {error}
          </div>
        )}

        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {!currentSession ? (
            <div className="h-full flex flex-col items-center justify-center text-center gap-4">
              <div className="text-4xl">🤱</div>
              <p className="text-gray-500 dark:text-gray-400 font-medium">Ask anything about your baby</p>
              <p className="text-sm text-gray-400 dark:text-gray-500">Tap ☰ to see past chats, or just type below to start</p>
              <Button onClick={createNewSession} className="mt-2 rounded-full">New Chat</Button>
            </div>
          ) : (currentSession.messages?.length ?? 0) === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-center gap-2">
              <p className="text-gray-400 dark:text-gray-500 text-sm">Type a question below to get started</p>
            </div>
          ) : (
            (currentSession.messages ?? []).map((msg, i) => (
              <div
                key={i}
                className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
              >
                <div className={`p-3 rounded-2xl max-w-[80%] text-sm whitespace-pre-wrap leading-relaxed
                  ${msg.role === "user"
                    ? "bg-rose-400 text-white rounded-br-sm"
                    : "bg-white dark:bg-gray-800 dark:text-gray-100 shadow-sm rounded-bl-sm"
                  }`}
                >
                  {msg.content}
                </div>
              </div>
            ))
          )}
          {loading && (
            <div className="flex justify-start">
              <div className="bg-white dark:bg-gray-800 p-3 rounded-2xl rounded-bl-sm shadow-sm">
                <div className="flex gap-1">
                  <span className="w-2 h-2 bg-gray-300 dark:bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "0ms" }} />
                  <span className="w-2 h-2 bg-gray-300 dark:bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "150ms" }} />
                  <span className="w-2 h-2 bg-gray-300 dark:bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "300ms" }} />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Input */}
        <div className="p-4 border-t bg-white dark:bg-gray-800 flex-shrink-0">
          <div className="flex items-center gap-2">
            {/* Input renders its own wrapper div, so flex-1 must go on a wrapper
                here — putting it on <Input> only hits the inner <input> (already
                w-full) and the wrapper stays content-width, leaving it narrow. */}
            <div className="flex-1">
              <Input
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={e => e.key === "Enter" && !e.shiftKey && handleSend()}
                placeholder="Ask about your baby..."
                disabled={loading}
              />
            </div>
            <Button onClick={handleSend} disabled={loading || !input.trim()} loading={loading}>
              Send
            </Button>
          </div>
        </div>
      </div>

      <ConfirmDialog
        open={!!deleteConfirm}
        onClose={() => setDeleteConfirm(null)}
        onConfirm={() => deleteConfirm && deleteSession(deleteConfirm)}
        title="Delete this conversation?"
        description="This can't be undone."
        confirmLabel="Delete"
        variant="danger"
      />
    </div>
  );
}
