import { createSignal, For, Show, onMount, onCleanup, createEffect } from "solid-js";

import { apiListPresence, apiUpdatePresence, apiClearPresence } from "~/lib/api-integrations";
import type { Presence } from "~/lib/types-integrations";
import { useApp } from "~/lib/app-context";

interface PresenceIndicatorProps {
  workspaceSlug: string;
  entityType?: string;
  entityId?: string;
  refreshInterval?: number; // milliseconds, default 10000 (10 seconds)
}

export function PresenceIndicator(props: PresenceIndicatorProps) {
  const app = useApp();
  const [presences, setPresences] = createSignal<Presence[]>([]);
  const [myPresence, setMyPresence] = createSignal<Presence | null>(null);
  const refreshInterval = () => props.refreshInterval || 10000;

  const loadPresence = async () => {
    try {
      const list = await apiListPresence(
        props.workspaceSlug,
        props.entityType || "",
        props.entityId || ""
      );
      setPresences(list.filter(p => p.userEmail !== app.state.session?.email));
    } catch (e) {
      console.error("Failed to load presence", e);
    }
  };

  const updateMyPresence = async () => {
    if (!app.state.session) return;
    try {
      const presence = await apiUpdatePresence({
        workspaceSlug: props.workspaceSlug,
        userEmail: app.state.session.email,
        userName: app.state.session.name,
        entityType: props.entityType,
        entityId: props.entityId
      });
      setMyPresence(presence);
    } catch (e) {
      console.error("Failed to update presence", e);
    }
  };

  const clearMyPresence = async () => {
    if (!app.state.session) return;
    try {
      await apiClearPresence(props.workspaceSlug);
    } catch (e) {
      console.error("Failed to clear presence", e);
    }
  };

  // Update presence when entity changes
  createEffect(() => {
    const _ = props.entityId; // track dependency
    const __ = props.entityType; // track dependency
    updateMyPresence();
    loadPresence();
  });

  onMount(() => {
    updateMyPresence();
    loadPresence();
    // Refresh presence periodically for real-time updates
    const interval = setInterval(() => {
      loadPresence();
      updateMyPresence(); // Keep our presence alive
    }, refreshInterval());
    onCleanup(() => {
      clearInterval(interval);
      clearMyPresence();
    });
  });

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map(n => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2);
  };

  const getColor = (email: string) => {
    const colors = [
      "bg-red-500",
      "bg-orange-500",
      "bg-amber-500",
      "bg-yellow-500",
      "bg-lime-500",
      "bg-green-500",
      "bg-emerald-500",
      "bg-teal-500",
      "bg-cyan-500",
      "bg-sky-500",
      "bg-blue-500",
      "bg-indigo-500",
      "bg-violet-500",
      "bg-purple-500",
      "bg-fuchsia-500",
      "bg-pink-500"
    ];
    const hash = email.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return colors[hash % colors.length];
  };

  return (
    <Show when={presences().length > 0}>
      <div class="flex items-center gap-1">
        <div class="flex -space-x-2">
          <For each={presences().slice(0, 4)}>
            {presence => (
              <div
                class={`w-7 h-7 rounded-full ${getColor(presence.userEmail)} flex items-center justify-center text-white text-xs font-medium ring-2 ring-[var(--surface)]`}
                title={`${presence.userName} is viewing`}
              >
                {getInitials(presence.userName)}
              </div>
            )}
          </For>
        </div>
        <Show when={presences().length > 4}>
          <span class="text-xs text-[var(--text-muted)] ml-1">
            +{presences().length - 4} more
          </span>
        </Show>
      </div>
    </Show>
  );
}