import { WindowControls } from "@/components/window-controls";
import { Button } from "@/components/ui/button";
import { Outlet, useLocation, useNavigate, useParams } from "react-router-dom";
import { Home, Settings } from "lucide-react";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useNetworks } from "@/hooks/use-networks";
import { particlePath, toFirestoreDocPath } from "@/lib/particle-path";
import { useLiveParticle, useParticle } from "@/hooks/use-particle";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { getParticle } from "@/lib/firestore-particles";
import type { Particle } from "@/api/types";

function getParticleDisplayName(particle: Particle): string {
  switch (particle.type) {
    case "stream":
    case "folder":
      return particle.properties.name;
    case "quest":
      return particle.properties.title;
    case "paper":
      return particle.properties.title;
    case "file":
      return particle.properties.filename;
    case "text":
      return particle.properties.content.slice(0, 30);
    case "media":
      return particle.type;
  }
}

function NetworkBreadcrumbContent({ networkId }: { networkId: string }) {
  const { data: networks } = useNetworks();
  const network = networks?.find((n) => n.id === networkId);
  const name = network?.name ?? networkId;
  const initials = name.slice(0, 2).toUpperCase();

  return (
    <span className="flex items-center gap-1.5">
      <Avatar size="sm">
        <AvatarFallback className="bg-primary/10 text-primary text-[10px] font-medium">
          {initials}
        </AvatarFallback>
      </Avatar>
      {name}
    </span>
  );
}

function TopBar() {
  const navigate = useNavigate();
  const { networkId, "*": rest } = useParams();
  const segments = [networkId, ...rest?.split("/") ?? []].filter(Boolean);

  const path = rest ? particlePath(networkId!, rest.split("/").filter(Boolean)) : undefined;

  const { data: particle } = useParticle(path);

  return (
    <div className="drag-region flex items-center gap-3 border-b px-3 py-1">
      <WindowControls />

      <Breadcrumb className="no-drag">
        <BreadcrumbList>
          <BreadcrumbItem className="text-xs">
            {segments.length === 0 ? (
              <BreadcrumbPage className="flex items-center gap-1">
                <Home className="size-3.5" />
              </BreadcrumbPage>
            ) : (
              <BreadcrumbLink
                className="flex cursor-pointer items-center gap-1"
                onClick={() => navigate("/")}
              >
                <Home className="size-3.5" />
              </BreadcrumbLink>
            )}
          </BreadcrumbItem>

          {networkId && (
            <span className="contents">
              <BreadcrumbSeparator />
              <BreadcrumbItem className="text-xs">
                {segments.length === 1 ? (
                  <BreadcrumbPage>
                    <NetworkBreadcrumbContent networkId={networkId} />
                  </BreadcrumbPage>
                ) : (
                  <BreadcrumbLink
                    className="cursor-pointer"
                    onClick={() => navigate(`/${networkId}`)}
                  >
                    <NetworkBreadcrumbContent networkId={networkId} />
                  </BreadcrumbLink>
                )}
              </BreadcrumbItem>
            </span>
          )}

          {particle && (
            <span key={path} className="contents">
              <BreadcrumbSeparator />
              <BreadcrumbItem className="text-xs">
                <BreadcrumbPage>{getParticleDisplayName(particle)}</BreadcrumbPage>
              </BreadcrumbItem>
            </span>
          )}
        </BreadcrumbList>
      </Breadcrumb>

      <div className="flex-1" />

      <Button
        variant="ghost"
        size="sm"
        className="no-drag text-muted-foreground"
        onClick={() => navigate("/settings")}
      >
        <Settings className="size-3.5" />
      </Button>
    </div>
  );
}

export default function Layout() {
  return (
    <div className="flex h-screen flex-col">
      <TopBar />
      <div className="relative flex-1 overflow-hidden">
        <Outlet />
      </div>
    </div>
  );
}
