import React, { useEffect, useState } from 'react';
import {
  TAB_LABELS,
  type NavEntry,
  type TabId,
  parseRoute,
  navigate,
  readHistory,
} from '../navigation';

interface NavHistoryBarProps {
  classLabel?: string;
  onBack: () => void;
}

export const NavHistoryBar: React.FC<NavHistoryBarProps> = ({ classLabel, onBack }) => {
  const [history, setHistory] = useState<NavEntry[]>([]);
  const route = parseRoute();

  useEffect(() => {
    const refresh = () => setHistory(readHistory());
    refresh();
    window.addEventListener('popstate', refresh);
    return () => window.removeEventListener('popstate', refresh);
  }, []);

  const currentTabLabel = TAB_LABELS[route.tab];
  const recent = history.slice(0, 6);

  const handlePillClick = (entry: NavEntry) => {
    if (entry.kind === 'class' && entry.classId) {
      navigate(entry.tab, entry.classId, entry.label, 'class');
    } else if (entry.kind === 'exam' && entry.examId) {
      navigate(entry.tab, entry.examId, entry.label, 'exam');
    } else {
      navigate(entry.tab);
    }
  };

  const isCurrent = (entry: NavEntry) => {
    if (entry.kind === 'class' && route.classId) {
      return entry.classId === route.classId;
    }
    if (entry.kind === 'exam' && route.examId) {
      return entry.examId === route.examId;
    }
    return entry.kind === 'tab' && !route.classId && !route.examId && entry.tab === route.tab;
  };

  return (
    <div className="nav-history-bar">
      <div className="breadcrumb-row">
        <button type="button" className="breadcrumb-back" onClick={onBack} title="Quay lại">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="16" height="16">
            <polyline points="15 18 9 12 15 6" />
          </svg>
          Quay lại
        </button>
        <span className="breadcrumb-sep">/</span>
        <button type="button" className="breadcrumb-link" onClick={() => navigate('dashboard')}>
          Simple Care
        </button>
        <span className="breadcrumb-sep">/</span>
        <button type="button" className="breadcrumb-link" onClick={() => navigate(route.tab)}>
          {currentTabLabel}
        </button>
        {route.classId && classLabel && (
          <>
            <span className="breadcrumb-sep">/</span>
            <span className="breadcrumb-current">{classLabel}</span>
          </>
        )}
      </div>

      {recent.length > 0 && (
        <div className="history-pills-row">
          <span className="history-pills-label">Gần đây</span>
          <div className="history-pills">
            {recent.map((entry, idx) => (
              <button
                key={entry.id}
                type="button"
                className={`history-pill ${isCurrent(entry) ? 'active' : ''}`}
                onClick={() => handlePillClick(entry)}
                title={entry.label}
              >
                <span className="history-pill-index">P{idx + 1}</span>
                <span className="history-pill-label">{entry.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export function useRoute() {
  const [route, setRoute] = useState(parseRoute);

  useEffect(() => {
    const onPop = () => setRoute(parseRoute());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  return route;
}

export function openClass(tab: TabId, classId: number, className: string) {
  navigate(tab, classId, className, 'class');
}

export function openExam(examId: number, examName: string) {
  navigate('exams', examId, examName, 'exam');
}

export function openTab(tab: TabId) {
  navigate(tab);
}
