"use client";

import { useCallback, useEffect, useState } from "react";
import { createClient, getBrowserUserId } from "@/lib/supabase/client";
import type { Tag } from "@/types";
import { useWorkspaceStore } from "@/stores/workspace-store";

export function useTags() {
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);
  const [userId, setUserId] = useState<string | null>(null);
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);

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

  const fetchTags = useCallback(async () => {
    if (!initialized) return;

    setLoading(true);

    let query = supabase
      .from("tags")
      .select("*")
      .order("name");

    query = activeTeamId
      ? query.eq("team_id", activeTeamId)
      : query.is("team_id", null);

    const { data } = await query;

    setTags(data || []);
    setLoading(false);
  }, [activeTeamId, initialized, supabase]);

  useEffect(() => {
    if (!initialized) return;
    const timer = window.setTimeout(() => {
      void fetchTags();
    }, 0);

    return () => window.clearTimeout(timer);
  }, [fetchTags, initialized]);

  async function createTag(name: string, color: string) {
    if (!userId) throw new Error("Not authenticated");

    const { data, error } = await supabase
      .from("tags")
      .insert({ name, color, user_id: userId, team_id: activeTeamId })
      .select()
      .single();
    if (error) throw error;
    setTags((prev) => [...prev, data]);
    return data as Tag;
  }

  async function deleteTag(id: string) {
    const { error } = await supabase.from("tags").delete().eq("id", id);
    if (error) throw error;
    setTags((prev) => prev.filter((t) => t.id !== id));
  }

  return { tags, loading, createTag, deleteTag, refetch: fetchTags };
}
