'use client';

import type { View } from '@/features/views/types';
import { cn } from '@/lib/utils/cn';
import { Icon } from './icons';

/** The built-in first tab. Custom objects have no system views, so this one lives on the page. */
export const ALL_RECORDS = 'all';

/** `.evl-views`: "All records", then the saved views of this object, then `+` (add a view). */
export function ViewTabs({
  views,
  selectedId,
  onSelect,
  onAdd,
  loading,
}: {
  views: View[];
  /** A view id, or ALL_RECORDS. */
  selectedId: string;
  onSelect: (id: string) => void;
  onAdd: () => void;
  loading: boolean;
}) {
  const tabs = [
    { id: ALL_RECORDS, name: 'All records', isShared: false },
    ...views.map((v) => ({ id: v.id, name: v.name, isShared: v.isShared })),
  ];
  return (
    <div className="evl-views" role="tablist" aria-label="Saved views">
      {tabs.map((tab) => {
        const active = tab.id === selectedId;
        return (
          <button
            key={tab.id}
            type="button"
            role="tab"
            aria-selected={active}
            className={cn('evl-view', active && 'is-active')}
            onClick={() => onSelect(tab.id)}
            title={tab.isShared ? `${tab.name} (shared)` : tab.name}
          >
            {tab.id === ALL_RECORDS ? <Icon name="table" size={12} /> : null}
            <span>{tab.name}</span>
          </button>
        );
      })}
      <button
        type="button"
        className="evl-views__add"
        aria-label="Add view"
        title="Add view"
        disabled={loading}
        onClick={onAdd}
      >
        <Icon name="plus" size={12} />
      </button>
    </div>
  );
}
