import { useEffect, useState, type ReactNode } from 'react';

type Tab = 'form' | 'raw';

type Props = {
  section: string;
  formNode: ReactNode;
  rawNode: ReactNode;
};

export function EditTabs({ section, formNode, rawNode }: Props) {
  const storageKey = `admin:tab:${section}`;
  const [tab, setTab] = useState<Tab>('form');

  useEffect(() => {
    const saved = sessionStorage.getItem(storageKey) as Tab | null;
    if (saved === 'form' || saved === 'raw') setTab(saved);
  }, [storageKey]);

  const switchTo = (t: Tab) => {
    setTab(t);
    sessionStorage.setItem(storageKey, t);
  };

  return (
    <div>
      <nav
        role="tablist"
        aria-label="Mode d'édition"
        className="flex gap-1 border-b border-[color:var(--color-border)] mb-6"
      >
        <TabButton
          active={tab === 'form'}
          onClick={() => switchTo('form')}
          label="Formulaire"
          tag="// guidé"
        />
        <TabButton
          active={tab === 'raw'}
          onClick={() => switchTo('raw')}
          label="JSON brut"
          tag="// avancé"
        />
      </nav>

      <div role="tabpanel" hidden={tab !== 'form'}>
        {tab === 'form' && formNode}
      </div>
      <div role="tabpanel" hidden={tab !== 'raw'}>
        {tab === 'raw' && rawNode}
      </div>
    </div>
  );
}

function TabButton({
  active,
  onClick,
  label,
  tag,
}: {
  active: boolean;
  onClick: () => void;
  label: string;
  tag: string;
}) {
  return (
    <button
      type="button"
      role="tab"
      aria-selected={active}
      onClick={onClick}
      className={`px-4 py-2 font-display uppercase tracking-widest text-sm transition-colors border-b-2 ${
        active
          ? 'text-[color:var(--color-acid)] border-[color:var(--color-acid)] glow-text-acid'
          : 'text-[color:var(--color-text-muted)] border-transparent hover:text-[color:var(--color-cyan)]'
      }`}
    >
      <span className="block leading-none">{label}</span>
      <span className="block font-mono text-[9px] opacity-70 mt-0.5">{tag}</span>
    </button>
  );
}
