"use client";

import { useSearchParams, useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { trpc } from "~/lib/trpc/client.js";

const OverviewTab = dynamic(() => import("./skills/OverviewTab.js").then((m) => ({ default: m.OverviewTab })), {
  loading: () => <div className="h-64 shimmer-skeleton rounded-xl" />,
});
const SearchTab = dynamic(() => import("./skills/SearchTab.js").then((m) => ({ default: m.SearchTab })), {
  loading: () => <div className="h-64 shimmer-skeleton rounded-xl" />,
});
const GapsTab = dynamic(() => import("./skills/GapsTab.js").then((m) => ({ default: m.GapsTab })), {
  loading: () => <div className="h-64 shimmer-skeleton rounded-xl" />,
});
const PeopleFinderTab = dynamic(() => import("./skills/PeopleFinderTab.js").then((m) => ({ default: m.PeopleFinderTab })), {
  loading: () => <div className="h-64 shimmer-skeleton rounded-xl" />,
});

const TABS = [
  { key: "overview", label: "Overview" },
  { key: "search", label: "Search" },
  { key: "gaps", label: "Gaps" },
  { key: "people", label: "People Finder" },
] as const;

type TabKey = (typeof TABS)[number]["key"];

export function SkillsHub() {
  const searchParams = useSearchParams();
  const router = useRouter();

  const rawTab = searchParams.get("tab");
  const activeTab: TabKey = TABS.some((t) => t.key === rawTab) ? (rawTab as TabKey) : "overview";

  function setTab(tab: TabKey) {
    const params = new URLSearchParams(searchParams.toString());
    params.set("tab", tab);
    router.replace(`/analytics/skills?${params.toString()}` as `/analytics/skills`, { scroll: false });
  }

  const { data, isLoading, error } = trpc.resource.getSkillsAnalytics.useQuery(undefined, { staleTime: 60_000 });

  if (isLoading) {
    return (
      <div className="p-6 space-y-4">
        <div className="h-8 shimmer-skeleton rounded w-64" />
        <div className="h-64 shimmer-skeleton rounded-xl" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-4 text-sm text-red-700 dark:text-red-300">
          {error.message}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 pb-24 space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Skills Hub</h1>
        <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
          {data?.totalResources} active resources &middot; {data?.totalSkillEntries} distinct skills
        </p>
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 border-b border-gray-200 dark:border-slate-700">
        {TABS.map((tab) => (
          <button
            key={tab.key}
            type="button"
            onClick={() => setTab(tab.key)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px ${
              activeTab === tab.key
                ? "border-brand-600 text-brand-600 dark:text-brand-400 dark:border-brand-400"
                : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-slate-600"
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === "overview" && data && (
        <OverviewTab
          aggregated={data.aggregated}
          categories={data.categories}
          totalResources={data.totalResources}
          totalSkillEntries={data.totalSkillEntries}
        />
      )}
      {activeTab === "search" && <SearchTab />}
      {activeTab === "gaps" && <GapsTab />}
      {activeTab === "people" && data && (
        <PeopleFinderTab
          allSkillNames={data.aggregated.map((e) => e.skill)}
          allChapters={data.allChapters}
        />
      )}
    </div>
  );
}
