"use client";

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

export function useMindset() {
  const [affirmations, setAffirmations] = useState<Affirmation[]>([]);
  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 fetchAll = useCallback(async () => {
    if (!initialized) return;

    const goalsQuery = activeTeamId
      ? supabase
          .from("goals")
          .select("*")
          .eq("team_id", activeTeamId)
          .order("completed")
          .order("sort_order")
          .order("created_at", { ascending: false })
      : supabase
          .from("goals")
          .select("*")
          .is("team_id", null)
          .order("completed")
          .order("sort_order")
          .order("created_at", { ascending: false });

    const [affRes, goalRes] = await Promise.all([
      supabase
        .from("affirmations")
        .select("*")
        .order("sort_order")
        .order("created_at"),
      goalsQuery,
    ]);
    setAffirmations(affRes.data || []);
    setGoals(goalRes.data || []);
    setLoading(false);
  }, [activeTeamId, initialized, supabase]);

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

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

  async function addAffirmation(text: string) {
    const currentUserId = await requireCurrentUserId();
    if (!currentUserId) return;
    const { data, error } = await supabase
      .from("affirmations")
      .insert({ user_id: currentUserId, text, sort_order: affirmations.length })
      .select()
      .single();
    if (!error && data) setAffirmations((prev) => [...prev, data]);
  }

  async function updateAffirmation(id: string, text: string) {
    await supabase.from("affirmations").update({ text }).eq("id", id);
    setAffirmations((prev) => prev.map((a) => (a.id === id ? { ...a, text } : a)));
  }

  async function deleteAffirmation(id: string) {
    await supabase.from("affirmations").delete().eq("id", id);
    setAffirmations((prev) => prev.filter((a) => a.id !== id));
  }

  async function addGoal(input: {
    title: string;
    description?: string;
    target_date?: string;
    color?: string;
    icon?: string;
  }) {
    const currentUserId = await requireCurrentUserId();
    if (!currentUserId) return;
    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 && data) setGoals((prev) => [data, ...prev]);
  }

  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) setGoals((prev) => prev.map((g) => (g.id === id ? { ...g, ...input } : g)));
  }

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

  return {
    affirmations,
    goals,
    loading,
    addAffirmation,
    updateAffirmation,
    deleteAffirmation,
    addGoal,
    updateGoal,
    deleteGoal,
    refetch: fetchAll,
  };
}
