import { clsx } from "clsx";
import { Tabs as TabsPrimitive } from "radix-ui";
import * as React from "react";
import { useEvent, useGetKey, useGetSet } from "../../hooks";

const TabsContext = React.createContext<{
  "data-variant": string;
  "data-size": string;
}>({
  "data-variant": "enclosed",
  "data-size": "md",
});
export const Tabs = ({
  className,
  defaultValue,
  variant = "enclosed",
  size = "md",
  ...props
}: TabsPrimitive.TabsProps & {
  variant?: "enclosed" | "line" | "subtle" | "outline";
  size?: "sm" | "md" | "lg";
}) => {
  const key = useGetKey(props as any);
  const initialValue = React.useMemo(
    () => ({ value: defaultValue as string | undefined }),
    [defaultValue],
  );
  const [{ value }, setState] = useGetSet<{
    value: string | undefined;
  }>(key, initialValue);
  const open = React.useCallback(
    (value: string) => {
      setState({ value }, process.env.PREVIEW ? `onPreviewToggle` : undefined);
    },
    [setState],
  );
  const id = props["data-id"];
  useEvent(id, "open", open);
  const ctx = React.useMemo(
    () => ({ "data-variant": variant, "data-size": size }),
    [variant, size],
  );
  return (
    <TabsContext value={ctx}>
      <TabsPrimitive.Root
        className={clsx("__tabs", className)}
        {...props}
        {...ctx}
        value={value}
        onValueChange={(value: string) => {
          setState(
            { value },
            process.env.PREVIEW ? `onValueChange` : undefined,
          );
        }}
      />
    </TabsContext>
  );
};

Tabs.TabsList = ({ className, ...props }: TabsPrimitive.TabsListProps) => {
  const themeProps = React.use(TabsContext);
  return (
    <TabsPrimitive.List
      data-tabs="list"
      className={clsx("__tabs-list", className)}
      {...themeProps}
      {...props}
    />
  );
};

Tabs.TabsTrigger = ({
  className,
  ...props
}: TabsPrimitive.TabsTriggerProps) => {
  const themeProps = React.use(TabsContext);
  return (
    <TabsPrimitive.Trigger
      data-tabs="trigger"
      className={clsx("__tabs-trigger", className)}
      {...themeProps}
      {...props}
    />
  );
};

Tabs.TabsContent = ({
  className,
  preview,
  ...props
}: TabsPrimitive.TabsContentProps & { preview?: true }) => {
  const themeProps = React.use(TabsContext);
  return (
    <TabsPrimitive.Content
      data-tabs="content"
      className={clsx("__tabs-content", className)}
      forceMount={preview}
      {...themeProps}
      {...props}
    />
  );
};
