import type { ReactNode } from "react";
import MuiTabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";
import Box from "@mui/material/Box";

export interface TabDef {
  value: string;
  label: string;
}

// Deterministic ids so the Tab control and its TabPanel can cross-reference for
// a11y (aria-controls <-> aria-labelledby). Values are app-controlled strings.
const tabId = (value: string) => `tab-${value}`;
const panelId = (value: string) => `tabpanel-${value}`;

/** Tab bar over MUI Tabs. Pair with <TabPanel> for the content. */
export function Tabs({
  value,
  onChange,
  tabs,
}: {
  value: string;
  onChange: (v: string) => void;
  tabs: TabDef[];
}) {
  return (
    <MuiTabs
      value={value}
      onChange={(_, v) => onChange(v)}
      sx={{
        borderBottom: 1,
        borderColor: "divider",
        minHeight: 44,
        "& .MuiTab-root": { textTransform: "none", fontWeight: 600 },
      }}
    >
      {tabs.map((t) => (
        <Tab
          key={t.value}
          value={t.value}
          label={t.label}
          id={tabId(t.value)}
          aria-controls={panelId(t.value)}
        />
      ))}
    </MuiTabs>
  );
}

/** Renders children only when its value matches the current tab. */
export function TabPanel({
  value,
  current,
  children,
}: {
  value: string;
  current: string;
  children: ReactNode;
}) {
  if (value !== current) return null;
  return (
    <Box
      role="tabpanel"
      id={panelId(value)}
      aria-labelledby={tabId(value)}
      sx={{ pt: 2.5 }}
    >
      {children}
    </Box>
  );
}
