import { Link } from "react-router-dom";
import { Suspense } from "react";
import { graphql, useLazyLoadQuery } from "react-relay";
import { Logo } from "./Logo.tsx";
import { Avatar } from "./Avatar.tsx";
import { Button } from "./Button.tsx";
import { logout, useSessionContext } from "../lib/useSession.ts";
import type { LayoutQuery } from "../__generated__/LayoutQuery.graphql.ts";

interface LayoutProps {
  children: React.ReactNode;
  headerChart?: React.ReactNode;
  subNav?: React.ReactNode;
}

function UserProfile({ handle }: { handle: string }) {
  const data = useLazyLoadQuery<LayoutQuery>(
    graphql`
      query LayoutQuery($where: NetworkSlicesActorProfileWhereInput) {
        networkSlicesActorProfiles(first: 1, where: $where) {
          edges {
            node {
              actorHandle
              avatar {
                url(preset: "avatar")
              }
            }
          }
        }
      }
    `,
    {
      where: {
        actorHandle: { eq: handle },
      },
    },
  );

  const profile = data.networkSlicesActorProfiles.edges[0]?.node;

  return (
    <>
      <Link
        to={`/profile/${handle}`}
        className="flex items-center gap-2 px-2 py-1 text-zinc-400 hover:text-zinc-300 transition-colors"
      >
        <Avatar
          src={profile?.avatar?.url}
          alt={handle}
          size="sm"
        />
        <span>@{handle}</span>
      </Link>
      <Link
        to="/docs"
        className="px-2 py-1 text-zinc-400 hover:text-zinc-300 transition-colors"
      >
        Docs
      </Link>
      <Button
        type="button"
        onClick={logout}
        variant="link"
        size="sm"
      >
        Sign Out
      </Button>
    </>
  );
}

export default function Layout({
  children,
  headerChart,
  subNav,
}: LayoutProps) {
  const { session } = useSessionContext();
  const isAuthenticated = session?.authenticated;
  const userInfo = session?.user;

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-300 font-mono">
      <div className="max-w-4xl mx-auto px-6 py-12">
        <div className="border-b border-zinc-800 pb-4 relative">
          {headerChart && (
            <div className="absolute inset-0 pointer-events-none opacity-40">
              {headerChart}
            </div>
          )}
          <div className="flex items-end justify-between relative">
            <Link
              to="/"
              className="flex items-center gap-3 hover:opacity-80 transition-opacity"
            >
              <Logo className="w-10 h-10" />
              <div>
                <h1 className="text-xs font-medium uppercase tracking-wider text-zinc-500">
                  Slices
                </h1>
                <p className="text-xs text-zinc-600 mt-1">network.slices</p>
              </div>
            </Link>

            <div className="flex gap-4 text-xs items-center">
              {isAuthenticated && userInfo
                ? (
                  <Suspense
                    fallback={
                      <span className="px-2 py-1 text-zinc-400">
                        @{userInfo.handle || userInfo.did}
                      </span>
                    }
                  >
                    <UserProfile handle={userInfo.handle || userInfo.did} />
                  </Suspense>
                )
                : (
                  <>
                    <Link
                      to="/waitlist"
                      className="px-2 py-1 text-zinc-500 hover:text-zinc-300 transition-colors"
                    >
                      Join Waitlist
                    </Link>
                    <Link
                      to="/login"
                      className="px-2 py-1 text-zinc-500 hover:text-zinc-300 transition-colors"
                    >
                      Sign In
                    </Link>
                  </>
                )}
            </div>
          </div>
        </div>

        {subNav && <div className="border-b border-zinc-800">{subNav}</div>}

        <div className="mb-4"></div>

        {children}
      </div>
    </div>
  );
}
