export type TabId = 'dashboard' | 'classes' | 'students' | 'learning' | 'exams' | 'network' | 'email-domains' | 'profile';

export interface NavEntry {
  id: string;
  kind: 'tab' | 'class' | 'exam';
  tab: TabId;
  classId?: number;
  examId?: number;
  label: string;
  timestamp: number;
}

export const TAB_LABELS: Record<TabId, string> = {
  dashboard: 'Tổng quan',
  classes: 'Lớp học',
  students: 'Sinh viên',
  learning: 'Giám sát & Lịch học',
  exams: 'Phòng thi',
  network: 'Quản lý mạng',
  'email-domains': 'Đuôi email',
  profile: 'Tài khoản của tôi',
};

const HISTORY_KEY = 'sc_nav_history';
const MAX_HISTORY = 10;

function isTabId(value: string | null): value is TabId {
  return value === 'dashboard' || value === 'classes' || value === 'students' || value === 'learning' || value === 'exams' || value === 'network' || value === 'email-domains' || value === 'profile';
}

export function parseRoute(): { tab: TabId; classId: number | null; examId: number | null } {
  const params = new URLSearchParams(window.location.search);
  const tabParam = params.get('tab');
  let tab: TabId = isTabId(tabParam) ? tabParam : 'dashboard';
  if (tabParam === 'accounts') tab = 'email-domains';
  const classIdRaw = params.get('classId');
  const classId = classIdRaw ? Number(classIdRaw) : null;
  const examIdRaw = params.get('examId');
  const examId = examIdRaw ? Number(examIdRaw) : null;
  return {
    tab,
    classId: classId && !Number.isNaN(classId) ? classId : null,
    examId: examId && !Number.isNaN(examId) ? examId : null,
  };
}

export function buildUrl(tab: TabId, classId?: number | null, examId?: number | null): string {
  const params = new URLSearchParams();
  params.set('tab', tab);
  if (classId) {
    params.set('classId', String(classId));
  }
  if (examId) {
    params.set('examId', String(examId));
  }
  return `/?${params.toString()}`;
}

export function readHistory(): NavEntry[] {
  try {
    const raw = sessionStorage.getItem(HISTORY_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw) as NavEntry[];
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

function writeHistory(entries: NavEntry[]) {
  sessionStorage.setItem(HISTORY_KEY, JSON.stringify(entries.slice(0, MAX_HISTORY)));
}

function entryKey(kind: NavEntry['kind'], tab: TabId, id?: number) {
  if (kind === 'class') return `class:${id}`;
  if (kind === 'exam') return `exam:${id}`;
  return `tab:${tab}`;
}

export function pushNav(entry: Omit<NavEntry, 'id' | 'timestamp'>) {
  const history = readHistory();
  const id = entryKey(entry.kind, entry.tab, entry.classId ?? entry.examId);
  const next: NavEntry = {
    ...entry,
    id,
    timestamp: Date.now(),
  };
  const filtered = history.filter((h) => h.id !== id);
  writeHistory([next, ...filtered]);
}

export function navigate(tab: TabId, id?: number | null, label?: string, kind: 'class' | 'exam' = 'class') {
  const url = kind === 'exam'
    ? buildUrl(tab, null, id)
    : buildUrl(tab, id);
  window.history.pushState({}, '', url);

  if (id && label) {
    pushNav({ kind, tab, classId: kind === 'class' ? id : undefined, examId: kind === 'exam' ? id : undefined, label });
  } else {
    pushNav({ kind: 'tab', tab, label: TAB_LABELS[tab] });
  }

  window.dispatchEvent(new PopStateEvent('popstate'));
}

export function goBack(fallbackTab: TabId = 'classes') {
  const history = readHistory();
  const current = parseRoute();
  const currentId = current.classId
    ? entryKey('class', current.tab, current.classId)
    : current.examId
      ? entryKey('exam', current.tab, current.examId)
      : entryKey('tab', current.tab);

  const remaining = history.filter((h) => h.id !== currentId);
  writeHistory(remaining);

  const previous = remaining[0];
  if (previous) {
    const url = previous.kind === 'class' && previous.classId
      ? buildUrl(previous.tab, previous.classId)
      : previous.kind === 'exam' && previous.examId
        ? buildUrl(previous.tab, null, previous.examId)
        : buildUrl(previous.tab);
    window.history.pushState({}, '', url);
  } else {
    window.history.pushState({}, '', buildUrl(fallbackTab));
  }
  window.dispatchEvent(new PopStateEvent('popstate'));
}
