"use client";

import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";
import type { PersonaInfo } from "./PersonaPicker";

export interface Message {
  role: "user" | "assistant";
  content: string;
  streaming?: boolean;
}

interface Props {
  persona: PersonaInfo;
  apiBase: string;
  messages: Message[];
  setMessages: Dispatch<SetStateAction<Message[]>>;
  sessionId: string | null;
  onSessionIdChange: (sessionId: string) => void;
}

export default function ChatPane({
  persona,
  apiBase,
  messages,
  setMessages,
  sessionId,
  onSessionIdChange,
}: Props) {
  const [input, setInput] = useState("");
  const [streaming, setStreaming] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);

  // Scroll to bottom on new messages
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const sendMessage = async () => {
    const text = input.trim();
    if (!text || streaming) return;
    setInput("");

    const userMsg: Message = { role: "user", content: text };
    setMessages((prev) => [...prev, userMsg]);

    const assistantMsg: Message = {
      role: "assistant",
      content: "",
      streaming: true,
    };
    setMessages((prev) => [...prev, assistantMsg]);
    setStreaming(true);

    try {
      const resp = await fetch(`${apiBase}/api/chat/${persona.slug}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: text, session_id: sessionId }),
      });

      if (!resp.ok || !resp.body) {
        throw new Error(`HTTP ${resp.status}`);
      }

      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        const lines = buffer.split("\n");
        buffer = lines.pop() ?? "";

        for (const line of lines) {
          if (!line.startsWith("data: ")) continue;
          const payload = JSON.parse(line.slice(6));
          if (payload.type === "session") {
            onSessionIdChange(payload.session_id);
          } else if (payload.type === "text") {
            setMessages((prev) => {
              const updated = [...prev];
              const last = updated[updated.length - 1];
              if (last.role === "assistant") {
                updated[updated.length - 1] = {
                  ...last,
                  content: last.content + payload.text,
                };
              }
              return updated;
            });
          } else if (payload.type === "done") {
            setMessages((prev) => {
              const updated = [...prev];
              const last = updated[updated.length - 1];
              if (last.role === "assistant") {
                updated[updated.length - 1] = { ...last, streaming: false };
              }
              return updated;
            });
          }
        }
      }
    } catch (err) {
      setMessages((prev) => {
        const updated = [...prev];
        const last = updated[updated.length - 1];
        if (last.role === "assistant") {
          updated[updated.length - 1] = {
            ...last,
            content: `[Error: ${String(err)}]`,
            streaming: false,
          };
        }
        return updated;
      });
    } finally {
      setStreaming(false);
    }
  };

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

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <span style={styles.headerName}>{persona.display_name}</span>
        <span style={styles.headerMeta}>text chat</span>
      </div>

      <div style={styles.messages}>
        {messages.length === 0 && (
          <div style={styles.empty}>
            Begin your conversation with {persona.display_name}.
          </div>
        )}
        {messages.map((msg, i) => (
          <div
            key={i}
            style={{
              ...styles.bubble,
              ...(msg.role === "user" ? styles.userBubble : styles.assistantBubble),
            }}
          >
            <span style={styles.role}>
              {msg.role === "user" ? "You" : persona.display_name}
            </span>
            <p style={styles.text}>
              {msg.content}
              {msg.streaming && <span style={styles.cursor}>▌</span>}
            </p>
          </div>
        ))}
        <div ref={bottomRef} />
      </div>

      <div style={styles.inputRow}>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder={`Ask ${persona.display_name} something…`}
          disabled={streaming}
          rows={2}
          style={styles.textarea}
        />
        <button
          onClick={sendMessage}
          disabled={streaming || !input.trim()}
          style={{
            ...styles.sendBtn,
            ...(streaming || !input.trim() ? styles.sendBtnDisabled : {}),
          }}
        >
          Send
        </button>
      </div>
    </div>
  );
}

const styles: Record<string, React.CSSProperties> = {
  container: {
    display: "flex",
    flexDirection: "column",
    height: "100%",
    background: "var(--bg)",
  },
  header: {
    padding: "14px 20px",
    borderBottom: "1px solid var(--border)",
    display: "flex",
    alignItems: "baseline",
    gap: "10px",
    background: "var(--surface)",
  },
  headerName: {
    fontWeight: 700,
    color: "var(--accent)",
    fontSize: "16px",
  },
  headerMeta: {
    color: "var(--text-muted)",
    fontSize: "12px",
  },
  messages: {
    flex: 1,
    overflowY: "auto",
    padding: "20px",
    display: "flex",
    flexDirection: "column",
    gap: "16px",
  },
  empty: {
    color: "var(--text-muted)",
    fontStyle: "italic",
    textAlign: "center",
    marginTop: "40px",
    fontSize: "14px",
  },
  bubble: {
    maxWidth: "700px",
    display: "flex",
    flexDirection: "column",
    gap: "4px",
  },
  userBubble: {
    alignSelf: "flex-end",
    alignItems: "flex-end",
  },
  assistantBubble: {
    alignSelf: "flex-start",
    alignItems: "flex-start",
  },
  role: {
    fontSize: "11px",
    color: "var(--text-muted)",
    fontWeight: 600,
    textTransform: "uppercase",
    letterSpacing: "0.05em",
  },
  text: {
    background: "var(--surface)",
    padding: "10px 14px",
    borderRadius: "var(--radius)",
    lineHeight: 1.65,
    fontSize: "14px",
    border: "1px solid var(--border)",
    whiteSpace: "pre-wrap",
  },
  cursor: {
    animation: "blink 1s step-end infinite",
    color: "var(--accent)",
  },
  inputRow: {
    display: "flex",
    gap: "8px",
    padding: "14px 20px",
    borderTop: "1px solid var(--border)",
    background: "var(--surface)",
  },
  textarea: {
    flex: 1,
    padding: "10px 14px",
    borderRadius: "var(--radius)",
    border: "1px solid var(--border)",
    background: "var(--bg)",
    color: "var(--text)",
    resize: "none",
    outline: "none",
  },
  sendBtn: {
    padding: "0 20px",
    background: "var(--accent)",
    color: "#000",
    borderRadius: "var(--radius)",
    fontWeight: 600,
    fontSize: "13px",
    transition: "opacity 0.15s",
  },
  sendBtnDisabled: {
    opacity: 0.4,
    cursor: "default",
  },
};
