import * as React from "react";
import { useState } from "react";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
  DropdownMenuPortal,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";

export type DynamicTabItem = {
  value: string;
  label: string;
};

export type DynamicTabsProps = {
  /** Full list of available tabs (selected + unselected). */
  allTabs: DynamicTabItem[];
  /** Values of the tabs currently shown in the bar. */
  selectedTabs: string[];
  /** Currently active tab value. */
  activeTab: string;
  onTabChange: (value: string) => void;
  /** Called when the user adds/removes tabs via the overflow dropdown. */
  onTabsChange?: (next: string[]) => void;
  /** Label for the overflow toggle button. */
  expandLabel?: string;
  className?: string;
};

export function DynamicTabs({
  allTabs,
  selectedTabs,
  activeTab,
  onTabChange,
  onTabsChange,
  expandLabel = "More",
  className,
}: DynamicTabsProps) {
  // Staged selections inside the dropdown (committed on close).
  const [staged, setStaged] = useState<Set<string>>(new Set());
  const [open, setOpen] = useState(false);

  const selectedSet = new Set(selectedTabs);

  const handleOpenChange = (next: boolean) => {
    if (!next && staged.size > 0) {
      // Commit: append new tabs preserving original order
      const ordered = allTabs
        .filter((t) => staged.has(t.value))
        .map((t) => t.value);
      onTabsChange?.([...selectedTabs, ...ordered]);
      setStaged(new Set());
    }
    setOpen(next);
  };

  const handleToggle = (value: string, checked: boolean) => {
    if (selectedSet.has(value)) return; // already shown — no-op
    setStaged((prev) => {
      const next = new Set(prev);
      checked ? next.add(value) : next.delete(value);
      return next;
    });
  };

  const hasOverflow = allTabs.some((t) => !selectedSet.has(t.value));

  return (
    // Outer wrapper is NOT role="tablist" — the dropdown must live outside it
    <div
      className={cn(
        "flex items-end gap-0 border-b border-border font-sans",
        className,
      )}
    >
      {/* Tab buttons only — valid children of tablist */}
      <div role="tablist" className="flex min-w-0 flex-1 items-end gap-0">
        {selectedTabs.map((value) => {
          const tab = allTabs.find((t) => t.value === value);
          if (!tab) return null;
          const isActive = value === activeTab;
          return (
            <button
              key={value}
              role="tab"
              aria-selected={isActive}
              onClick={() => onTabChange(value)}
              className={cn(
                "relative shrink-0 cursor-pointer px-4 py-2.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                isActive
                  ? "border-b-2 border-primary text-foreground"
                  : "border-b-2 border-transparent text-muted-foreground hover:text-foreground",
              )}
            >
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Overflow dropdown lives outside the tablist to satisfy aria-required-children */}
      {hasOverflow && (
        <DropdownMenu open={open} onOpenChange={handleOpenChange}>
          <DropdownMenuTrigger className="mb-px shrink-0 inline-flex items-center gap-1 px-3 py-2 text-sm font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
            {expandLabel}
            <ChevronDownIcon className="size-3" />
          </DropdownMenuTrigger>
          <DropdownMenuPortal>
            <DropdownMenuContent align="end" className="min-w-48">
              {allTabs.map((tab) => (
                <DropdownMenuCheckboxItem
                  key={tab.value}
                  checked={selectedSet.has(tab.value) || staged.has(tab.value)}
                  disabled={selectedSet.has(tab.value)}
                  onCheckedChange={(checked) =>
                    handleToggle(tab.value, checked)
                  }
                >
                  {tab.label}
                </DropdownMenuCheckboxItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenuPortal>
        </DropdownMenu>
      )}
    </div>
  );
}

function ChevronDownIcon({ className }: { className?: string }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}
