import { useState, useEffect, useMemo } from "react";
import {
  subscribeToParticle,
  subscribeToParticleChildren,
  subscribeToLatestChild,
  getParticle,
} from "@/lib/firestore-particles";
import type { Particle } from "@/api/types";
import {
  type ParticlePath,
  toFirestoreDocPath,
  toFirestoreChildrenPath,
} from "@/lib/particle-path";
import { useQuery } from "@tanstack/react-query";

interface UseLiveParticleResult {
  particle: Particle | null;
  isLoading: boolean;
  error: Error | null;
}

export function useLiveParticle(path: ParticlePath): UseLiveParticleResult {
  const [particle, setParticle] = useState<Particle | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const docPath = useMemo(() => toFirestoreDocPath(path), [path]);

  useEffect(() => {
    setIsLoading(true);
    setError(null);
    setParticle(null);

    const unsubscribe = subscribeToParticle(
      docPath,
      (data) => {
        setParticle(data);
        setIsLoading(false);
      },
      (err) => {
        setError(err);
        setIsLoading(false);
      },
    );

    return unsubscribe;
  }, [docPath]);

  return { particle, isLoading, error };
}

interface UseLiveParticleChildrenResult {
  children: Particle[];
  isLoading: boolean;
  error: Error | null;
}

export function useLiveParticleChildren(
  path: ParticlePath,
  orderByField: string = "created_at",
  orderDirection: "asc" | "desc" = "desc",
): UseLiveParticleChildrenResult {
  const [children, setChildren] = useState<Particle[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const collectionPath = useMemo(() => toFirestoreChildrenPath(path), [path]);

  useEffect(() => {
    setIsLoading(true);
    setError(null);
    setChildren([]);

    const unsubscribe = subscribeToParticleChildren(
      collectionPath,
      (data) => {
        setChildren(data);
        setIsLoading(false);
      },
      (err) => {
        setError(err);
        setIsLoading(false);
      },
      orderByField,
      orderDirection,
    );

    return unsubscribe;
  }, [collectionPath]);

  return { children, isLoading, error };
}

interface UseLiveLatestChildResult {
  latestChild: Particle | null;
  isLoading: boolean;
}

export function useLiveLatestChild(path: ParticlePath): UseLiveLatestChildResult {
  const [latestChild, setLatestChild] = useState<Particle | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const collectionPath = useMemo(() => toFirestoreChildrenPath(path), [path]);

  useEffect(() => {
    setIsLoading(true);
    setLatestChild(null);

    const unsubscribe = subscribeToLatestChild(
      collectionPath,
      (data) => {
        setLatestChild(data);
        setIsLoading(false);
      },
      () => {
        setIsLoading(false);
      },
    );

    return unsubscribe;
  }, [collectionPath]);

  return { latestChild, isLoading };
}

export function useParticle(path?: ParticlePath) {
  return useQuery({
    queryKey: ["particle", path],
    queryFn: async () => {
      if (!path) return null;
      const docPath = toFirestoreDocPath(path);
      const particle = await getParticle(docPath);
      return particle;
    },
    enabled: !!path,
  });
}
