import { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Lock } from "lucide-react";
import { useLiveParticle } from "@/hooks/use-particle";
import { particlePath } from "@/lib/particle-path";
import { Button } from "@/components/ui/button";

import { StreamView } from "@/features/particles/stream-view";
import { FolderView } from "@/features/particles/folder-view";


/**
 * Route-level component for /:networkId/*.
 * Reads params from the router, resolves the particle, and renders
 * the appropriate view based on particle type.
 */
export default function ParticleViewResolver() {
  const { networkId, "*": rest } = useParams();
  const segments = (rest ?? "").split("/").filter(Boolean);
  const path = particlePath(networkId!, segments); // path of current container particle

  const { particle, isLoading, error } = useLiveParticle(path);

  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-muted-foreground text-sm">Loading...</p>
      </div>
    );
  }

  if (error || !particle) {
    // Errors here are almost always Firestore permission-denied — the user lost
    // access to the network or to a custom-visibility particle. The React Router
    // stays on the dead route, so without an explicit escape the user is stuck.
    return <InaccessibleParticle />;
  }

  switch (particle.type) {
    case "stream":
      return <StreamView streamParticle={particle} path={path} />;
    case "folder":
      return <FolderView folderParticle={particle} path={path} />;
    default:
      return (
        <div className="flex h-full items-center justify-center">
          <p className="text-muted-foreground text-sm">
            {particle.type} particle: {particle.id}
          </p>
        </div>
      );
  }
}

function InaccessibleParticle() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  useEffect(() => {
    // Refresh the networks list so the home page reflects current access.
    queryClient.invalidateQueries({ queryKey: ["networks"] });
  }, [queryClient]);

  return (
    <div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
      <Lock className="text-muted-foreground size-8" />
      <div className="flex max-w-sm flex-col gap-1">
        <p className="text-sm font-medium">This particle isn't available</p>
        <p className="text-muted-foreground text-xs">
          It may have been deleted, or your access was removed.
        </p>
      </div>
      <Button size="sm" onClick={() => navigate("/", { replace: true })}>
        Go home
      </Button>
    </div>
  );
}
