"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useSession } from "next-auth/react";
import { cn } from "@/lib/utils";
import type { HumanCapitalWorkspaceTabConfig } from "@/lib/human-capital/types";

const DEFAULT_TABS: HumanCapitalWorkspaceTabConfig[] = [
  { key: "resumen", label: "Resumen", order: 0, visible: true, widgets: ["summary_metrics"] },
  { key: "expedientes", label: "Expedientes", order: 1, visible: true, widgets: ["people_files_table"] },
  { key: "nomina", label: "Nomina", order: 2, visible: true, widgets: ["payroll_summary"] },
  { key: "reclutamiento", label: "Reclutamiento", order: 3, visible: true, widgets: ["recruitment_headcount"] },
  { key: "desarrollo", label: "Desarrollo", order: 4, visible: true, widgets: ["career_feed"] },
  { key: "cumplimiento", label: "Cumplimiento", order: 5, visible: true, widgets: ["compliance_overview"] },
];

export default function HumanCapitalWorkspaceTabs() {
  const pathname = usePathname();
  const { data: session } = useSession();
  const [tabs, setTabs] = useState<HumanCapitalWorkspaceTabConfig[]>(DEFAULT_TABS);

  const canManage =
    session?.user?.role === "owner" ||
    (session?.user?.role === "leader" &&
      (session?.user?.department === "capital_humano" || session?.user?.department === "administracion"));

  useEffect(() => {
    let cancelled = false;

    async function load() {
      try {
        const response = await fetch("/api/human-capital/workspace/config", {
          method: "GET",
          cache: "no-store",
        });

        const payload = (await response.json()) as { config?: { tabs?: HumanCapitalWorkspaceTabConfig[] } };
        if (!cancelled && response.ok && payload.config?.tabs) {
          setTabs(payload.config.tabs);
        }
      } catch {
        if (!cancelled) {
          setTabs(DEFAULT_TABS);
        }
      }
    }

    void load();
    return () => {
      cancelled = true;
    };
  }, []);

  const visibleTabs = useMemo(() => tabs.filter((tab) => tab.visible), [tabs]);

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <p className="text-xs font-semibold uppercase tracking-wide text-benell-brown">Capital Humano</p>
        {canManage ? (
          <Link
            href="/departments/human-capital/configuracion"
            className="text-label font-semibold text-benell-brown hover:text-black"
          >
            Configurar workspace
          </Link>
        ) : null}
      </div>
      <div className="mt-3 flex flex-wrap gap-2">
        {visibleTabs.map((tab) => {
          const href = `/departments/human-capital/${tab.key}`;
          const isActive = pathname === href || pathname.startsWith(`${href}/`);
          return (
            <Link
              key={tab.key}
              href={href}
              className={cn(
                "inline-flex items-center rounded-full px-3 py-1.5 text-sm font-semibold transition",
                isActive ? "bg-benell-brown text-white" : "bg-benell-surface-muted text-benell-text hover:bg-benell-brown/10"
              )}
            >
              {tab.label}
            </Link>
          );
        })}
      </div>
    </section>
  );
}
