"use client";

import { useCallback, useEffect, useState } from "react";
import { createClient, getBrowserUserId } from "@/lib/supabase/client";
import type { ProjectLink } from "@/types";
import { logProjectActivity } from "@/lib/project-activity";

export function useProjectLinks(projectId: string) {
  const [links, setLinks] = useState<ProjectLink[]>([]);
  const [loading, setLoading] = useState(true);
  const [userId, setUserId] = useState<string | null>(null);
  const supabase = createClient();

  useEffect(() => {
    void getBrowserUserId().then(setUserId).catch(() => setUserId(null));
  }, []);

  async function requireCurrentUserId() {
    const currentUserId = userId || (await getBrowserUserId());
    if (currentUserId && currentUserId !== userId) {
      setUserId(currentUserId);
    }
    return currentUserId;
  }

  const fetchLinks = useCallback(async () => {
    const { data } = await supabase
      .from("project_links")
      .select("*")
      .eq("project_id", projectId)
      .order("sort_order")
      .order("created_at", { ascending: false });

    setLinks(data || []);
    setLoading(false);
  }, [projectId, supabase]);

  useEffect(() => {
    async function loadLinks() {
      await fetchLinks();
    }
    void loadLinks();
  }, [fetchLinks]);

  async function createLink(input: {
    title: string;
    url: string;
    kind?: string;
  }) {
    const currentUserId = await requireCurrentUserId();
    if (!currentUserId) throw new Error("Not authenticated");

    const { data, error } = await supabase
      .from("project_links")
      .insert({
        user_id: currentUserId,
        project_id: projectId,
        title: input.title,
        url: input.url,
        kind: input.kind || "link",
        sort_order: links.length,
      })
      .select()
      .single();

    if (error) throw error;
    await logProjectActivity(supabase, {
      userId: currentUserId,
      projectId,
      entityType: "link",
      entityId: data.id,
      action: "link_created",
      title: data.title,
      details: { url: data.url, kind: data.kind },
    });
    await fetchLinks();
    return data as ProjectLink;
  }

  async function deleteLink(id: string) {
    const existing = links.find((link) => link.id === id);
    const currentUserId = await requireCurrentUserId();
    const { error } = await supabase.from("project_links").delete().eq("id", id);
    if (error) throw error;
    await logProjectActivity(supabase, {
      userId: currentUserId,
      projectId,
      entityType: "link",
      entityId: id,
      action: "link_deleted",
      title: existing?.title || "Link deleted",
    });
    await fetchLinks();
  }

  async function reorderLinks(nextLinks: ProjectLink[]) {
    const currentUserId = await requireCurrentUserId();
    await Promise.all(
      nextLinks.map((link, index) =>
        supabase.from("project_links").update({ sort_order: index }).eq("id", link.id)
      )
    );
    setLinks(nextLinks.map((link, index) => ({ ...link, sort_order: index })));
    await logProjectActivity(supabase, {
      userId: currentUserId,
      projectId,
      entityType: "link",
      action: "links_reordered",
      title: "Project links reordered",
    });
  }

  return {
    links,
    loading,
    createLink,
    deleteLink,
    reorderLinks,
    refetch: fetchLinks,
  };
}
