import { useState } from "preact/hooks";
import type { ComponentChildren } from "preact";

interface Tab {
  label: string;
  icon?: string;
  content: ComponentChildren;
}

interface TabContainerProps {
  tabs: Tab[];
  style?: "line" | "button";
  defaultTab?: number;
}

export function TabContainer({ tabs, style = "line", defaultTab = 0 }: TabContainerProps) {
  const [active, setActive] = useState(defaultTab);

  return (
    <div class="mb-4">
      {/* Tab headers */}
      <div class="flex gap-0.5 mb-4" style={style === "line" ? { borderBottom: "1px solid var(--z-border)" } : {}}>
        {tabs.map((tab, i) => {
          const isActive = i === active;
          if (style === "button") {
            return (
              <button
                key={i}
                onClick={() => setActive(i)}
                class="px-3 py-1.5 text-xs rounded-md transition-all"
                style={{
                  background: isActive ? "var(--z-accent-dim)" : "var(--z-card-bg)",
                  color: isActive ? "var(--z-accent-light)" : "var(--z-muted)",
                  border: isActive ? "1px solid var(--z-accent-border)" : "1px solid var(--z-border)",
                  fontWeight: isActive ? 500 : 400,
                }}
              >
                {tab.icon && <span class="mr-1">{tab.icon}</span>}
                {tab.label}
              </button>
            );
          }
          // Line style
          return (
            <button
              key={i}
              onClick={() => setActive(i)}
              class="px-3 py-2 text-xs transition-all -mb-px"
              style={{
                color: isActive ? "var(--z-accent-light)" : "var(--z-muted)",
                borderBottom: isActive ? "2px solid var(--z-accent)" : "2px solid transparent",
                fontWeight: isActive ? 500 : 400,
              }}
            >
              {tab.icon && <span class="mr-1">{tab.icon}</span>}
              {tab.label}
            </button>
          );
        })}
      </div>
      {/* Tab content */}
      {tabs[active]?.content}
    </div>
  );
}
