"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link";
import { useAccount } from "@/contexts/AccountContext";

type Msg = {
  id: string;
  sender: string;
  text: string;
  time: string;
  mine: boolean;
};

const SEED_MSGS: Omit<Msg, "mine">[] = [
  { id: "s1", sender: "void_cartographer", text: "Anyone else notice the latency on the east relay dropped by 40ms this cycle?", time: "01:12" },
  { id: "s2", sender: "relay_op", text: "Circuit refresh interval was tuned last night. Should hold for 72h.", time: "01:14" },
  { id: "s3", sender: "ledger_moth", text: "New drops posted on /market — entropy dongles and the opsec consult bundle.", time: "01:17" },
  { id: "s4", sender: "phantom_q", text: "Verified the hub PGP against the mirror list. All checksums matched.", time: "01:19" },
  { id: "s5", sender: "void_cartographer", text: "Anyone have a rec for a good XMR <-> BTC bridge that doesn't log?", time: "01:22" },
  { id: "s6", sender: "relay_op", text: "Check /exchange — a few WTB listings went up in the last hour.", time: "01:24" },
];

const AUTO_REPLIES = [
  "Received. Check your vault for any pending receipts.",
  "Noted. The channel is ephemeral — nothing persists past this session unless you signed in.",
  "Copy that. See /forum for threaded discussion on that topic.",
  "Market is up. Check /drops for the latest scheduled releases.",
  "Circuit healthy. Reply latency nominal.",
  "Acknowledged. Keep OPSEC tight and verify mirrors before each session.",
];

const CHAT_KEY = "cyberlux-chat-v1";

function now() {
  return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

function uid() {
  return Math.random().toString(36).slice(2, 10);
}

function loadHistory(): Msg[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = localStorage.getItem(CHAT_KEY);
    if (!raw) return [];
    return JSON.parse(raw) as Msg[];
  } catch {
    return [];
  }
}

function saveHistory(msgs: Msg[]) {
  if (typeof window === "undefined") return;
  localStorage.setItem(CHAT_KEY, JSON.stringify(msgs.slice(-80)));
}

export default function ChatWidget() {
  const { user } = useAccount();
  const handle = user?.displayName ?? user?.username ?? "anon";

  const [messages, setMessages] = useState<Msg[]>([]);
  const [input, setInput] = useState("");
  const [hydrated, setHydrated] = useState(false);
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const stored = loadHistory();
    if (stored.length > 0) {
      setMessages(stored);
    } else {
      const seeded = SEED_MSGS.map((m) => ({ ...m, mine: false }));
      setMessages(seeded);
      saveHistory(seeded);
    }
    setHydrated(true);
  }, []);

  useEffect(() => {
    if (hydrated && messages.length > 0) {
      saveHistory(messages);
      endRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, hydrated]);

  const send = useCallback(() => {
    const text = input.trim();
    if (!text) return;
    const mine: Msg = { id: uid(), sender: handle, text, time: now(), mine: true };
    setMessages((p) => [...p, mine]);
    setInput("");
    const delay = 900 + Math.random() * 900;
    setTimeout(() => {
      const replyText = AUTO_REPLIES[Math.floor(Math.random() * AUTO_REPLIES.length)]!;
      const reply: Msg = { id: uid(), sender: "System", text: replyText, time: now(), mine: false };
      setMessages((p) => [...p, reply]);
    }, delay);
  }, [input, handle]);

  return (
    <div className="glass rounded-3xl border border-white/10 p-8">
      <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h2 className="font-orbitron text-3xl font-bold">CHANNEL CHAT</h2>
          <p className="mt-1 text-sm text-foreground/60">
            Ephemeral hub channel — stored locally.{" "}
            {user ? (
              <span className="text-neon-cyan">Posting as @{user.username}</span>
            ) : (
              <Link href="/sign-in" className="text-neon-cyan underline">
                Sign in to tag your handle
              </Link>
            )}
          </p>
        </div>
        <div className="flex gap-3 text-[10px] font-mono uppercase tracking-wider text-foreground/40">
          <span className="flex items-center gap-1">
            <span className="inline-block h-2 w-2 animate-pulse rounded-full bg-neon-green" />
            channel active
          </span>
          <span>local store</span>
        </div>
      </div>

      <div className="mb-4 h-72 overflow-y-auto rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3">
        {messages.map((msg) => (
          <div key={msg.id} className={`flex flex-col ${msg.mine ? "items-end" : "items-start"}`}>
            <div className="mb-0.5 flex items-center gap-2">
              <span
                className={`text-xs font-medium ${
                  msg.mine
                    ? "text-neon-cyan"
                    : msg.sender === "System"
                    ? "text-neon-purple"
                    : "text-foreground/70"
                }`}
              >
                {msg.mine ? `@${handle}` : msg.sender === "System" ? "⚡ System" : `@${msg.sender}`}
              </span>
              <span className="text-[10px] text-foreground/30">{msg.time}</span>
            </div>
            <div
              className={`max-w-[80%] rounded-2xl px-4 py-2 text-sm ${
                msg.mine
                  ? "bg-neon-cyan/15 text-neon-cyan"
                  : msg.sender === "System"
                  ? "bg-neon-purple/10 text-neon-purple/90"
                  : "bg-white/5 text-foreground/90"
              }`}
            >
              {msg.text}
            </div>
          </div>
        ))}
        <div ref={endRef} />
      </div>

      <div className="flex gap-3">
        <input
          type="text"
          className="flex-1 rounded-2xl border border-white/10 bg-black/40 px-5 py-3 text-sm focus:border-neon-cyan/40 focus:outline-none"
          placeholder={user ? `Message as @${user.username}…` : "Message the channel…"}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && send()}
          maxLength={500}
        />
        <button
          type="button"
          onClick={send}
          disabled={!input.trim()}
          className="rounded-2xl bg-gradient-to-r from-neon-cyan to-neon-purple px-6 py-3 text-sm font-bold text-background disabled:opacity-40"
        >
          Send
        </button>
      </div>

      <div className="mt-6 grid grid-cols-2 gap-4 md:grid-cols-4">
        {[
          { icon: "🔒", label: "Client storage", sub: "Never leaves your browser" },
          { icon: "💬", label: "Open channel", sub: "Hub-wide thread" },
          { icon: "📬", label: "Forum threads", sub: "/forum for persistence" },
          { icon: "📦", label: "Market drops", sub: "/drops for schedule" },
        ].map((f) => (
          <div key={f.label} className="glass rounded-2xl border border-white/10 p-4 text-center">
            <div className="text-2xl">{f.icon}</div>
            <div className="mt-2 text-sm font-bold">{f.label}</div>
            <div className="text-xs text-foreground/50">{f.sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}
