"use client";

import { useEffect, useMemo, useRef, useState } from "react";

interface ChatMessage {
  id: string;
  name: string;
  message: string;
  createdAt: string;
}

export function CommunityChat() {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [name, setName] = useState("Guest");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const listRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const es = new EventSource("/api/chat/stream");
    es.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === "init") {
        setMessages(data.items || []);
      }
      if (data.type === "message") {
        setMessages((prev) => [...prev, data.item].slice(-200));
      }
    };
    es.onerror = () => {
      es.close();
    };
    return () => es.close();
  }, []);

  useEffect(() => {
    listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
  }, [messages]);

  const canSend = useMemo(() => message.trim().length > 0 && message.length <= 250, [message]);

  async function send() {
    setError("");
    if (!canSend) return;

    const res = await fetch("/api/chat/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, message }),
    });

    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError(data.error || "Gagal mengirim.");
      return;
    }

    setMessage("");
  }

  return (
    <section className="glass-strong rounded-2xl p-4 md:p-6">
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-display font-bold text-lg">Community Chat</h2>
        <span className="text-xs text-muted-foreground">Real-time</span>
      </div>

      <div ref={listRef} className="h-64 overflow-y-auto space-y-3 pr-1">
        {messages.map((msg) => (
          <div key={msg.id} className="bg-card/60 rounded-xl p-3">
            <div className="text-xs text-muted-foreground mb-1">
              {msg.name} - {new Date(msg.createdAt).toLocaleTimeString("id-ID")}
            </div>
            <div className="text-sm">{msg.message}</div>
          </div>
        ))}
        {messages.length === 0 && (
          <div className="text-sm text-muted-foreground">Belum ada pesan.</div>
        )}
      </div>

      <div className="mt-4 space-y-2">
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="search-input"
          placeholder="Nama (opsional)"
          maxLength={32}
        />
        <textarea
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          className="search-input min-h-[88px]"
          placeholder="Tulis pesan (maks 250 karakter)"
          maxLength={250}
        />
        {error && <div className="text-xs text-destructive">{error}</div>}
        <button
          className="inline-flex items-center justify-center rounded-full bg-primary text-black px-4 py-2 font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
          onClick={send}
          disabled={!canSend}
        >
          Kirim
        </button>
      </div>
    </section>
  );
}
