import { graphql, useLazyLoadQuery } from "react-relay";
import { Link, NavLink, useParams } from "react-router-dom";
import { useMemo, type PropsWithChildren } from "react";
import type { ProfileLayoutQuery as ProfileLayoutQueryType } from "./__generated__/ProfileLayoutQuery.graphql";
import ScrobbleChart from "./ScrobbleChart";

export default function ProfileLayout({ children }: PropsWithChildren) {
  const { handle } = useParams<{ handle: string }>();

  const queryVariables = useMemo(() => {
    // Round to start of day to keep timestamp stable
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const ninetyDaysAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);

    return {
      where: { actorHandle: { eq: handle } },
      chartWhere: {
        actorHandle: { eq: handle },
        playedTime: {
          gte: ninetyDaysAgo.toISOString(),
        },
      },
    };
  }, [handle]);

  const queryData = useLazyLoadQuery<ProfileLayoutQueryType>(
    graphql`
      query ProfileLayoutQuery($where: FmTealAlphaFeedPlayWhereInput!, $chartWhere: FmTealAlphaFeedPlayWhereInput!) {
        ...ScrobbleChart_data
        fmTealAlphaFeedPlays(
          first: 1
          sortBy: [{ field: playedTime, direction: desc }]
          where: $where
        ) {
          edges {
            node {
              actorHandle
              appBskyActorProfile {
                displayName
                description
                avatar {
                  url(preset: "avatar")
                }
              }
            }
          }
        }
      }
    `,
    queryVariables
  );

  const profile = queryData?.fmTealAlphaFeedPlays?.edges?.[0]?.node?.appBskyActorProfile;

  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">
        <Link
          to="/"
          className="px-2 py-1 text-xs text-zinc-500 hover:text-zinc-300 transition-colors inline-block mb-8"
        >
          ← Back
        </Link>

        <div className="mb-12 border-b border-zinc-800 pb-6 relative">
          <div className="absolute inset-0 pointer-events-none opacity-40">
            <ScrobbleChart queryRef={queryData} />
          </div>
          <div className="relative flex items-start gap-6">
            {profile?.avatar?.url && (
              <img
                src={profile.avatar.url}
                alt={profile.displayName ?? handle ?? "User"}
                className="w-16 h-16 flex-shrink-0 object-cover"
              />
            )}
            <div className="flex-1">
              <h1 className="text-lg font-medium mb-1 text-zinc-100">
                {profile?.displayName ?? handle}
              </h1>
              <p className="text-xs text-zinc-500 mb-2">@{handle}</p>
              {profile?.description && (
                <p className="text-xs text-zinc-400">{profile.description}</p>
              )}
            </div>
          </div>
        </div>

        <div className="flex items-center border-b border-zinc-800 mb-8">
          <NavLink
            to={`/profile/${handle}/scrobbles`}
            className={({ isActive }) =>
              `px-4 py-2 text-xs uppercase tracking-wider ${
                isActive ? "text-zinc-100 border-b-2 border-zinc-100" : "text-zinc-500 hover:text-zinc-300"
              }`
            }
          >
            Scrobbles
          </NavLink>
          <NavLink
            to={`/profile/${handle}/overall`}
            className={({ isActive }) =>
              `px-4 py-2 text-xs uppercase tracking-wider ${
                isActive ? "text-zinc-100 border-b-2 border-zinc-100" : "text-zinc-500 hover:text-zinc-300"
              }`
            }
          >
            Overall
          </NavLink>
        </div>

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