'use client';

import { useState } from 'react';
import { useSession } from 'next-auth/react';
import ProductsView from './views/ProductsView';
import InventoryView from './views/InventoryView';
import PantryView from './views/PantryView';

type TableId = 'inventory' | 'pantry' | 'products';

type TableDef = {
  id: TableId;
  label: string;
  adminOnly: boolean;
};

const TABLES: TableDef[] = [
  { id: 'inventory', label: '🏠 Inventarie', adminOnly: false },
  { id: 'pantry', label: '📦 Baslager', adminOnly: false },
  { id: 'products', label: '🗄️ Produkter', adminOnly: true },
];

const tabStyle = (active: boolean): React.CSSProperties => ({
  padding: '0.5rem 1.1rem',
  border: 'none',
  borderBottom: active ? '2.5px solid #2563eb' : '2.5px solid transparent',
  background: active ? '#eff6ff' : 'none',
  cursor: 'pointer',
  fontWeight: active ? 600 : 400,
  color: active ? '#2563eb' : '#555',
  fontSize: '0.95rem',
  borderRadius: '4px 4px 0 0',
  transition: 'color 0.15s, border-color 0.15s, background 0.15s',
});

export default function DatabsTab() {
  const { data: session } = useSession();
  const isAdmin = (session?.user as any)?.role === 'admin';

  const visibleTables = TABLES.filter((t) => !t.adminOnly || isAdmin);

  const [activeTable, setActiveTable] = useState<TableId>('inventory');

  // Om vald tabell inte är tillgänglig för rollen, fall tillbaka på första
  const safeActive = visibleTables.find((t) => t.id === activeTable)
    ? activeTable
    : visibleTables[0]?.id ?? 'inventory';

  return (
    <div>
      {/* Tabellväljare */}
      <div
        style={{
          display: 'flex',
          gap: '0.25rem',
          borderBottom: '1px solid #ddd',
          marginBottom: '1.75rem',
        }}
      >
        {visibleTables.map((table) => (
          <button
            key={table.id}
            style={tabStyle(safeActive === table.id)}
            onClick={() => setActiveTable(table.id)}
          >
            {table.label}
          </button>
        ))}
      </div>

      {safeActive === 'inventory' && <InventoryView />}
      {safeActive === 'pantry' && <PantryView />}
      {safeActive === 'products' && isAdmin && <ProductsView />}
    </div>
  );
}

