"use client";

import { useCallback, useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import type { Profile, TeamAuditEntry } from "@/types";

export function useTeamAudit(teamId: string | null) {
  const [entries, setEntries] = useState<TeamAuditEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const supabase = createClient();

  const fetchEntries = useCallback(async () => {
    if (!teamId) {
      setEntries([]);
      setLoading(false);
      return;
    }

    setLoading(true);

    const { data, error } = await supabase
      .from("team_audit_log")
      .select("*")
      .eq("team_id", teamId)
      .order("created_at", { ascending: false })
      .limit(40);

    if (error) {
      console.error("Failed to load team audit log", error);
      setLoading(false);
      return;
    }

    const rawEntries = (data || []) as TeamAuditEntry[];
    const actorIds = Array.from(
      new Set(rawEntries.map((entry) => entry.actor_id).filter(Boolean))
    ) as string[];

    let profileMap = new Map<string, Profile>();
    if (actorIds.length > 0) {
      const { data: profilesData, error: profilesError } = await supabase
        .from("profiles")
        .select("id, email, full_name, avatar_url, created_at, updated_at")
        .in("id", actorIds);

      if (!profilesError) {
        profileMap = new Map(
          ((profilesData || []) as Profile[]).map((profile) => [profile.id, profile])
        );
      }
    }

    setEntries(
      rawEntries.map((entry) => ({
        ...entry,
        actor: entry.actor_id ? profileMap.get(entry.actor_id) || null : null,
      }))
    );
    setLoading(false);
  }, [supabase, teamId]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void fetchEntries();
    }, 0);

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

  useEffect(() => {
    if (!teamId) return;

    const channelName = `team-audit:${teamId}:${Math.random()
      .toString(36)
      .slice(2, 8)}`;
    const channel = supabase
      .channel(channelName)
      .on(
        "postgres_changes",
        {
          event: "*",
          schema: "public",
          table: "team_audit_log",
          filter: `team_id=eq.${teamId}`,
        },
        () => {
          void fetchEntries();
        }
      )
      .subscribe();

    return () => {
      void supabase.removeChannel(channel);
    };
  }, [fetchEntries, supabase, teamId]);

  return {
    entries,
    loading,
    refetch: fetchEntries,
  };
}
