import { useAuth } from "@/context/auth-context";
import { useQuery } from "@tanstack/react-query";
import { client } from "@/client";
import { CalendarDays, GitFork, Folder, Star, Users } from "lucide-react";
import { Link } from "react-router";
import { workspaceInitial } from "@/components/shell/shared";
import { ContributionHeatmap } from "./heatmap";
import { WorkspaceList, ActivityFeed } from "./activity";

export default function MeOverviewPage() {
  const { me } = useAuth();
  const username = me?.username ?? "";

  const { data: summary } = useQuery({
    queryKey: ["me", "summary", username],
    queryFn: async () => {
      const res = await client.usersUserSummary(username);
      return res.data;
    },
    enabled: Boolean(username),
    retry: false,
  });

  const { data: workspaces } = useQuery({
    queryKey: ["workspace", "my"],
    queryFn: async () => {
      const res = await client.workspaceMyWorkspaces();
      return res.data;
    },
    retry: false,
  });

  const { data: relationCounts } = useQuery({
    queryKey: ["me", "relations", username],
    queryFn: async () => {
      const res = await client.usersRelationCounts(username);
      return res.data;
    },
    enabled: Boolean(username),
    retry: false,
  });

  const displayName = summary?.display_name ?? me?.display_name ?? username;
  const avatarUrl = summary?.avatar_url ?? me?.avatar_url;
  const createdAt = summary?.created_at;
  const websiteUrl = summary?.website_url;

  const joinDate = createdAt
    ? new Date(createdAt).toLocaleDateString("en-US", { month: "short", year: "numeric" })
    : "";

  return (
    <div className="mx-auto max-w-4xl px-8 py-10">
      {/* Profile header */}
      <div className="flex items-center gap-5">
        <div className="grid size-16 place-items-center overflow-hidden rounded-xl bg-gradient-to-br text-xl font-heading font-bold text-white ring-1 ring-black/5 shadow-sm">
          {avatarUrl ? (
            <img alt="" className="size-full object-cover" src={avatarUrl} />
          ) : (
            workspaceInitial(displayName)
          )}
        </div>
        <div className="min-w-0">
          <h1 className="text-xl font-heading font-bold text-foreground truncate">{displayName}</h1>
          <p className="font-mono text-sm text-muted-foreground">@{username}</p>
          <div className="mt-3 flex items-center gap-3">
            {joinDate && (
              <span className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground">
                <CalendarDays className="size-3.5" />
                Joined {joinDate}
              </span>
            )}
            {websiteUrl && (
              <a
                className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-primary hover:border-primary/30 transition-colors"
                href={websiteUrl}
                target="_blank"
                rel="noopener noreferrer"
              >
                {websiteUrl.replace(/^https?:\/\//, "")}
              </a>
            )}
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="mt-8 grid grid-cols-4 gap-3">
        {[
          { value: workspaces?.length ?? 0, label: "Workspaces", icon: Folder, to: "/me/repos" },
          { value: 0, label: "Repositories", icon: GitFork, to: "/me/repos" },
          { value: 0, label: "Stars", icon: Star, to: "/me/stars" },
          { value: relationCounts?.followers ?? 0, label: "Followers", icon: Users, to: "/me/following" },
        ].map((stat) => (
          <Link
            className="group rounded-lg border border-border bg-card px-4 py-3 transition-colors hover:border-primary/20"
            key={stat.label}
            to={stat.to}
          >
            <div className="flex items-center justify-between">
              <p className="text-lg font-heading font-bold text-foreground">{stat.value}</p>
              <stat.icon className="size-3.5 text-muted-foreground group-hover:text-primary transition-colors" />
            </div>
            <p className="mt-1 font-mono text-[10px] uppercase tracking-widest text-muted-foreground">
              {stat.label}
            </p>
          </Link>
        ))}
      </div>

      {/* Contribution heatmap */}
      <ContributionHeatmap />

      {/* Bottom: Workspaces + Activity */}
      <div className="mt-16 grid grid-cols-2 gap-12">
        <WorkspaceList workspaces={workspaces} />
        <ActivityFeed relationCounts={relationCounts} />
      </div>
    </div>
  );
}