"use client";

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

export function useGoals() {
  const [goals, setGoals] = useState<Goal[]>([]);
  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));
  }, []);

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

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

    setLoading(true);

    let query = supabase
      .from("goals")
      .select("*")
      .order("completed")
      .order("sort_order")
      .order("created_at", { ascending: false });

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

    const { data } = await query;
    setGoals((data || []) as Goal[]);
    setLoading(false);
  }, [activeTeamId, initialized, supabase]);

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

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

  async function createGoal(input: {
    title: string;
    description?: string;
    target_date?: string;
    color?: string;
    icon?: string;
  }) {
    const currentUserId = await requireCurrentUserId();
    if (!currentUserId) throw new Error("Not authenticated");

    const { data, error } = await supabase
      .from("goals")
      .insert({
        user_id: currentUserId,
        team_id: activeTeamId,
        title: input.title,
        description: input.description || null,
        target_date: input.target_date || null,
        color: input.color || "#6366f1",
        icon: input.icon || "🎯",
        sort_order: goals.length,
      })
      .select()
      .single();

    if (error) throw error;
    setGoals((prev) => [data as Goal, ...prev]);
    return data as Goal;
  }

  async function updateGoal(
    id: string,
    input: Partial<
      Pick<
        Goal,
        "title" | "description" | "target_date" | "progress" | "color" | "icon" | "completed"
      >
    >
  ) {
    const { error } = await supabase.from("goals").update(input).eq("id", id);
    if (error) throw error;
    setGoals((prev) => prev.map((goal) => (goal.id === id ? { ...goal, ...input } : goal)));
  }

  async function deleteGoal(id: string) {
    const { error } = await supabase.from("goals").delete().eq("id", id);
    if (error) throw error;
    setGoals((prev) => prev.filter((goal) => goal.id !== id));
  }

  return {
    goals,
    loading,
    createGoal,
    updateGoal,
    deleteGoal,
    refetch: fetchGoals,
  };
}
