import type { TenantEvent } from '../api';
import {
  ADMIN_EVENT_INVITES_PATH,
  ADMIN_EVENT_PHOTOBOOTH_PATH,
  ADMIN_EVENT_CONTROL_ROOM_PATH,
  ADMIN_EVENT_TASKS_PATH,
  ADMIN_EVENT_VIEW_PATH,
  ADMIN_EVENT_RECAP_PATH,
  ADMIN_EVENT_BRANDING_PATH,
} from '../constants';

export type EventTabCounts = Partial<{
  photos: number;
  tasks: number;
}>;

type Translator = any;

export function buildEventTabs(event: TenantEvent, translate: Translator, counts: EventTabCounts = {}) {
  if (!event.slug) {
    return [];
  }

  const eventDate = event.event_date ? new Date(event.event_date) : null;
  const hasPassed = eventDate ? eventDate.getTime() <= Date.now() : false;

  const hasBranding = (() => {
    const settings = (event.settings ?? {}) as Record<string, unknown>;
    const brandingAllowed = Boolean(settings.branding_allowed ?? true);
    const packageAllowsBranding = brandingAllowed || settings.branding_allowed === undefined;
    return packageAllowsBranding;
  })();

  const formatBadge = (value?: number | null): number | undefined => {
    if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
      return value;
    }
    return undefined;
  };

  const tabs = [
    {
      key: 'overview',
      label: translate('eventMenu.summary', 'Übersicht'),
      href: ADMIN_EVENT_VIEW_PATH(event.slug),
    },
    {
      key: 'photos',
      label: translate('eventMenu.photos', 'Uploads'),
      href: ADMIN_EVENT_CONTROL_ROOM_PATH(event.slug),
      badge: formatBadge(counts.photos),
    },
    {
      key: 'tasks',
      label: translate('eventMenu.tasks', 'Aufgaben'),
      href: ADMIN_EVENT_TASKS_PATH(event.slug),
      badge: formatBadge(counts.tasks),
    },
    {
      key: 'invites',
      label: translate('eventMenu.invites', 'QR-Codes'),
      href: ADMIN_EVENT_INVITES_PATH(event.slug),
    },
    {
      key: 'photobooth',
      label: translate('eventMenu.photobooth', 'Photobooth'),
      href: ADMIN_EVENT_PHOTOBOOTH_PATH(event.slug),
    },
    ...(hasPassed
      ? [{
          key: 'recap',
          label: translate('eventMenu.recap', 'Nachbereitung'),
          href: ADMIN_EVENT_RECAP_PATH(event.slug),
        }]
      : []),
  ];

  if (hasBranding) {
    tabs.splice(4, 0, {
      key: 'branding',
      label: translate('eventMenu.branding', 'Branding'),
      href: ADMIN_EVENT_BRANDING_PATH(event.slug),
    });
  }

  return tabs;
}
