"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import {
  MessageSquare,
  X,
  Send,
  Share2,
  Trash2,
  Sparkles,
  Users,
  Crown,
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { getProfilePath } from "@/lib/constants";

export type ChatUser = {
  id: string;
  username: string;
  avatar_url?: string | null;
  is_premium?: boolean;
  is_promoter?: boolean;
};

export type ChatMessage = {
  id: string;
  user_id: string;
  username: string;
  avatar_url?: string | null;
  is_premium?: boolean;
  is_promoter?: boolean;
  message: string;
  created_at: string;
};

type Props = {
  currentUser: ChatUser;
};

function formatTime(iso: string) {
  try {
    const d = new Date(iso);
    return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  } catch {
    return "";
  }
}

// Renders message text, transforming sinss.lol/@user or sinss.lol/user into clickable pills
function MessageBody({ text }: { text: string }) {
  const parts = text.split(/(https?:\/\/[^\s]+|sinss\.lol\/[a-zA-Z0-9_.-]+)/g);

  return (
    <span style={{ wordBreak: "break-word" }}>
      {parts.map((part, i) => {
        if (!part) return null;
        const match = part.match(/(?:https?:\/\/)?(?:www\.)?sinss\.lol\/([a-zA-Z0-9_.-]+)/i);
        if (match) {
          const targetUser = match[1];
          return (
            <Link
              key={i}
              href={`/${targetUser}`}
              target="_blank"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "2px 7px",
                margin: "0 2px",
                borderRadius: 6,
                background: "rgba(216, 120, 120, 0.16)",
                border: "1px solid rgba(216, 120, 120, 0.35)",
                color: "#ffffff",
                textDecoration: "none",
                fontWeight: 650,
                fontSize: 11,
                verticalAlign: "middle",
              }}
            >
              <span>sinss.lol/{targetUser}</span>
            </Link>
          );
        }
        if (/^https?:\/\//i.test(part)) {
          return (
            <a
              key={i}
              href={part}
              target="_blank"
              rel="noopener noreferrer"
              style={{ color: "#ffffff", textDecoration: "underline" }}
            >
              {part}
            </a>
          );
        }
        return <span key={i}>{part}</span>;
      })}
    </span>
  );
}

export default function GlobalChat({ currentUser }: Props) {
  const supabase = useMemo(() => createClient(), []);
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [onlineCount, setOnlineCount] = useState(1);
  const [unreadCount, setUnreadCount] = useState(0);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const channelRef = useRef<ReturnType<typeof supabase.channel> | null>(null);

  // Fetch initial history
  useEffect(() => {
    fetch("/api/sys/chat")
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data.messages)) {
          setMessages(data.messages);
        }
      })
      .catch(() => undefined);
  }, []);

  // Connect to Supabase Realtime for live messages & presence
  useEffect(() => {
    const channel = supabase.channel("global-community-chat", {
      config: {
        presence: { key: currentUser.id },
      },
    });

    channelRef.current = channel;

    channel
      .on(
        "postgres_changes",
        { event: "INSERT", schema: "public", table: "global_chat_messages" },
        (payload) => {
          const newMsg = payload.new as ChatMessage;
          if (!newMsg || !newMsg.id) return;
          setMessages((prev) => {
            if (prev.some((m) => m.id === newMsg.id)) return prev;
            return [...prev, newMsg];
          });
          if (!isOpen) {
            setUnreadCount((c) => c + 1);
          }
        }
      )
      .on(
        "postgres_changes",
        { event: "DELETE", schema: "public", table: "global_chat_messages" },
        (payload) => {
          const deletedId = (payload.old as { id?: string })?.id;
          if (deletedId) {
            setMessages((prev) => prev.filter((m) => m.id !== deletedId));
          }
        }
      )
      .on("presence", { event: "sync" }, () => {
        const state = channel.presenceState();
        const count = Object.keys(state).length;
        setOnlineCount(Math.max(1, count));
      })
      .subscribe(async (status) => {
        if (status === "SUBSCRIBED") {
          await channel.track({
            user_id: currentUser.id,
            username: currentUser.username,
            online_at: new Date().toISOString(),
          });
        }
      });

    return () => {
      supabase.removeChannel(channel);
    };
  }, [currentUser, supabase, isOpen]);

  // Scroll to bottom when messages change and open
  useEffect(() => {
    if (isOpen) {
      setUnreadCount(0);
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [isOpen, messages]);

  const sendMessage = async (customText?: string) => {
    const textToSend = typeof customText === "string" ? customText.trim() : input.trim();
    if (!textToSend || sending) return;

    setError("");
    setSending(true);

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

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Could not send message.");
        return;
      }

      if (data.message) {
        // Optimistically add and broadcast
        setMessages((prev) => {
          if (prev.some((m) => m.id === data.message.id)) return prev;
          return [...prev, data.message];
        });



        if (!customText) {
          setInput("");
        }
      }
    } catch {
      setError("Network error sending message.");
    } finally {
      setSending(false);
    }
  };

  const shareProfileLink = () => {
    const profileUrl = `sinss.lol/${currentUser.username}`;
    void sendMessage(`Check out my page: ${profileUrl}`);
  };

  const deleteMessage = async (msgId: string) => {
    try {
      const res = await fetch(`/api/sys/chat?id=${msgId}`, { method: "DELETE" });
      if (res.ok) {
        setMessages((prev) => prev.filter((m) => m.id !== msgId));

      }
    } catch {
      // Ignored
    }
  };

  return (
    <>
      {/* Floating Toggle Button */}
      {!isOpen && (
        <button
          type="button"
          onClick={() => setIsOpen(true)}
          className="globalChatTrigger"
          style={{
            position: "fixed",
            zIndex: 9999,
            display: "flex",
            alignItems: "center",
            gap: 9,
            borderRadius: 999,
            background: "linear-gradient(135deg, #775c5c 0%, #0d1220 100%)",
            border: "1px solid rgba(216, 120, 120, 0.4)",
            boxShadow: "0 12px 36px rgba(0,0,0,0.55), 0 0 20px rgba(216, 120, 120, 0.18)",
            color: "#c20707",
            font: "inherit",
            fontSize: 13,
            fontWeight: 700,
            cursor: "pointer",
            transition: "transform .15s ease, box-shadow .15s ease",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.transform = "scale(1.03)")}
          onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
        >
          <div style={{ position: "relative", display: "grid", placeItems: "center" }}>
            <MessageSquare size={17} color="#f8cbcb" />
            <span
              style={{
                position: "absolute",
                top: -2,
                right: -3,
                width: 7,
                height: 7,
                borderRadius: "50%",
                background: "#de8383",
                boxShadow: "0 0 6px #de8383",
              }}
            />
          </div>
          <span>Live Chat</span>
          <span
            className="globalChatOnlineText"
            style={{
              fontSize: 11,
              color: "#882020",
              alignItems: "center",
              gap: 4,
            }}
          >
            <Users size={12} /> {onlineCount}
          </span>
          {unreadCount > 0 && (
            <span
              style={{
                padding: "2px 6px",
                borderRadius: 999,
                background: "#d87878",
                color: "#000",
                fontSize: 10,
                fontWeight: 800,
              }}
            >
              {unreadCount}
            </span>
          )}
        </button>
      )}

      {/* Expanded Chat Box */}
      {isOpen && (
        <div
          style={{
            position: "fixed",
            bottom: 84,
            right: "min(22px, 4vw)",
            zIndex: 9999,
            width: "min(390px, calc(100vw - 24px))",
            height: "min(530px, calc(100dvh - 98px))",
            display: "flex",
            flexDirection: "column",
            background: "#0a0e18",
            border: "1px solid #624444",
            borderRadius: 18,
            boxShadow: "0 24px 60px rgba(0,0,0,0.7), 0 0 24px rgba(216, 120, 120, 0.14)",
            overflow: "hidden",
            fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
          }}
        >
          {/* Header */}
          <div
            style={{
              padding: "12px 14px",
              background: "linear-gradient(180deg, #121929 0%, #0d1322 100%)",
              borderBottom: "1px solid #634747",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <div
                style={{
                  width: 30,
                  height: 30,
                  borderRadius: 9,
                  background: "rgba(216, 120, 120, 0.15)",
                  border: "1px solid rgba(216, 120, 120, 0.3)",
                  display: "grid",
                  placeItems: "center",
                  color: "#f8cbcb",
                }}
              >
                <MessageSquare size={15} />
              </div>
              <div>
                <strong style={{ display: "block", fontSize: 13, color: "#fa2626", fontWeight: 750 }}>
                  Community Shoutbox
                </strong>
                <span
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 5,
                    fontSize: 11,
                    color: "#de8383",
                    fontWeight: 600,
                  }}
                >
                  <span
                    style={{
                      width: 6,
                      height: 6,
                      borderRadius: "50%",
                      background: "#de8383",
                      boxShadow: "0 0 6px #de8383",
                    }}
                  />
                  {onlineCount} {onlineCount === 1 ? "member" : "members"} online
                </span>
              </div>
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <button
                type="button"
                onClick={() => setIsOpen(false)}
                title="Minimize chat"
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: 8,
                  background: "#6c5252",
                  border: "1px solid #603d3d",
                  color: "#6f1515",
                  display: "grid",
                  placeItems: "center",
                  cursor: "pointer",
                }}
              >
                <X size={14} />
              </button>
            </div>
          </div>

          {/* Messages Area */}
          <div
            style={{
              flex: 1,
              overflowY: "auto",
              padding: "14px 12px",
              display: "flex",
              flexDirection: "column",
              gap: 12,
              background: "#080c16",
            }}
          >
            {messages.length === 0 ? (
              <div
                style={{
                  margin: "auto",
                  textAlign: "center",
                  color: "#471717",
                  fontSize: 12,
                  padding: 20,
                }}
              >
                <MessageSquare size={28} style={{ margin: "0 auto 8px", opacity: 0.4 }} />
                <p style={{ margin: "0 0 4px", fontWeight: 600, color: "#661717" }}>No messages yet</p>
                <p style={{ margin: 0, fontSize: 11 }}>Be the first to say hello or share your bio link!</p>
              </div>
            ) : (
              messages.map((m) => {
                const isOwn = m.user_id === currentUser.id;
                return (
                  <div
                    key={m.id}
                    style={{
                      display: "flex",
                      alignItems: "flex-start",
                      gap: 9,
                      padding: "5px 8px",
                      borderRadius: 10,
                      background: m.is_promoter
                        ? "rgba(216, 123, 123, 0.06)"
                        : m.is_premium
                        ? "rgba(246, 230, 230, 0.05)"
                        : isOwn
                        ? "rgba(216, 120, 120, 0.05)"
                        : "transparent",
                      borderLeft: m.is_promoter
                        ? "2px solid rgba(216, 123, 123, 0.7)"
                        : m.is_premium
                        ? "2px solid rgba(246, 230, 230, 0.5)"
                        : "2px solid transparent",
                    }}
                  >
                    {/* Avatar */}
                    <div
                      style={{
                        width: 28,
                        height: 28,
                        borderRadius: "50%",
                        overflow: "hidden",
                        background: "#6e5252",
                        border: m.is_promoter
                          ? "1.5px solid rgba(216, 123, 123, 0.75)"
                          : m.is_premium
                          ? "1.5px solid rgba(246, 230, 230, 0.7)"
                          : "1px solid #6c4343",
                        boxShadow: m.is_promoter
                          ? "0 0 8px rgba(216, 123, 123, 0.35)"
                          : m.is_premium
                          ? "0 0 8px rgba(246, 230, 230, 0.3)"
                          : "none",
                        display: "grid",
                        placeItems: "center",
                        fontSize: 11,
                        fontWeight: 700,
                        color: m.is_promoter ? "#d87b7b" : m.is_premium ? "#fdf6f6" : "#ffffff",
                        flexShrink: 0,
                      }}
                    >
                      {m.avatar_url ? (
                        <img
                          src={m.avatar_url}
                          alt=""
                          style={{ width: "100%", height: "100%", objectFit: "cover" }}
                        />
                      ) : (
                        (m.username || "?").slice(0, 1).toUpperCase()
                      )}
                    </div>

                    {/* Content */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          gap: 6,
                          marginBottom: 2,
                        }}
                      >
                        <div style={{ display: "flex", alignItems: "center", gap: 5, overflow: "hidden" }}>
                          <Link
                            href={getProfilePath(m.username)}
                            target="_blank"
                            style={{
                              color: m.is_promoter
                                ? "#d87b7b"
                                : m.is_premium
                                ? "#fdf6f6"
                                : isOwn
                                ? "#ffffff"
                                : "#a60a0a",
                              fontSize: 12,
                              fontWeight: 700,
                              textDecoration: "none",
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                              textShadow: m.is_promoter
                                ? "0 0 10px rgba(216, 123, 123, 0.3)"
                                : m.is_premium
                                ? "0 0 10px rgba(246, 230, 230, 0.25)"
                                : "none",
                            }}
                          >
                            {m.username}
                          </Link>
                          {m.is_premium && (
                            <span
                              title="Sinss Premium Member"
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                gap: 3,
                                padding: "1px 6px",
                                borderRadius: 4,
                                background: "rgba(246, 230, 230, 0.16)",
                                border: "1px solid rgba(246, 230, 230, 0.35)",
                                color: "#fdf6f6",
                                fontSize: 9,
                                fontWeight: 800,
                                textTransform: "uppercase",
                                letterSpacing: ".02em",
                              }}
                            >
                              <Crown size={9} /> Premium
                            </span>
                          )}
                          {m.is_promoter && (
                            <span
                              title="Promoter (sinss.lol in status)"
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                gap: 3,
                                padding: "1px 6px",
                                borderRadius: 4,
                                background: "rgba(216, 123, 123, 0.16)",
                                border: "1px solid rgba(216, 123, 123, 0.35)",
                                color: "#d87b7b",
                                fontSize: 9,
                                fontWeight: 800,
                                textTransform: "uppercase",
                                letterSpacing: ".02em",
                              }}
                            >
                              <span>⚡</span> Promoter
                            </span>
                          )}
                        </div>

                        <div style={{ display: "flex", alignItems: "center", gap: 5, flexShrink: 0 }}>
                          <span style={{ fontSize: 10, color: "#4b1c1c" }}>{formatTime(m.created_at)}</span>
                          {isOwn && (
                            <button
                              type="button"
                              onClick={() => deleteMessage(m.id)}
                              title="Delete message"
                              style={{
                                background: "none",
                                border: "none",
                                color: "#4d1b1b",
                                cursor: "pointer",
                                padding: 2,
                                display: "grid",
                                placeItems: "center",
                              }}
                            >
                              <Trash2 size={11} />
                            </button>
                          )}
                        </div>
                      </div>

                      <div
                        style={{
                          fontSize: 12,
                          lineHeight: 1.45,
                          color: "#8d0e0e",
                        }}
                      >
                        <MessageBody text={m.message} />
                      </div>
                    </div>
                  </div>
                );
              })
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Quick Action: Share Profile Link */}
          <div
            style={{
              padding: "6px 12px",
              background: "#0c111f",
              borderTop: "1px solid #624848",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <button
              type="button"
              onClick={shareProfileLink}
              disabled={sending}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "4px 9px",
                borderRadius: 7,
                background: "rgba(216, 120, 120, 0.12)",
                border: "1px solid rgba(216, 120, 120, 0.35)",
                color: "#ffffff",
                fontSize: 11,
                fontWeight: 700,
                cursor: sending ? "wait" : "pointer",
              }}
            >
              <Share2 size={12} />
              <span>Share profile link</span>
            </button>

            <span style={{ fontSize: 10, color: "#4b1a1a" }}>sinss.lol/{currentUser.username}</span>
          </div>

          {/* Upsell for non-premium members */}
          {!currentUser.is_premium && (
            <div
              style={{
                padding: "6px 12px",
                background: "rgba(246, 230, 230, 0.05)",
                borderTop: "1px solid rgba(246, 230, 230, 0.12)",
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                fontSize: 11,
                color: "#fdf6f6",
              }}
            >
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                <Sparkles size={11} /> Stand out with a gold handle & Premium badge
              </span>
              <Link
                href="/premium"
                target="_blank"
                style={{
                  color: "#fdf6f6",
                  fontWeight: 700,
                  textDecoration: "underline",
                  fontSize: 11,
                  flexShrink: 0,
                }}
              >
                Upgrade
              </Link>
            </div>
          )}

          {/* Input Bar */}
          <div
            style={{
              padding: "10px 12px",
              background: "#090d18",
              borderTop: "1px solid #6e5252",
            }}
          >
            {error && (
              <p style={{ color: "#f8d6d6", fontSize: 11, margin: "0 0 6px", lineHeight: 1.3 }}>
                {error}
              </p>
            )}

            <form
              onSubmit={(e) => {
                e.preventDefault();
                void sendMessage();
              }}
              style={{ display: "flex", alignItems: "center", gap: 7 }}
            >
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="Say something to the community…"
                maxLength={300}
                disabled={sending}
                style={{
                  flex: 1,
                  height: 38,
                  padding: "0 12px",
                  borderRadius: 10,
                  background: "#0f1524",
                  border: "1px solid #613f3f",
                  color: "#fa2626",
                  fontSize: 14,
                  outline: "none",
                }}
              />
              <button
                type="submit"
                disabled={!input.trim() || sending}
                style={{
                  width: 38,
                  height: 38,
                  borderRadius: 10,
                  background: input.trim() ? "#d87878" : "#674b4b",
                  border: "1px solid",
                  borderColor: input.trim() ? "#e69595" : "#653f3f",
                  color: input.trim() ? "#000" : "#4e1919",
                  display: "grid",
                  placeItems: "center",
                  cursor: input.trim() && !sending ? "pointer" : "default",
                  transition: "background .15s",
                }}
              >
                <Send size={15} />
              </button>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
