import { useEffect } from 'react';
import { DashboardTab } from './components/DashboardTab';
import { ClassesTab } from './components/ClassesTab';
import { StudentsTab } from './components/StudentsTab';
import { LearningTab } from './components/LearningTab';
import { ExamsTab } from './components/ExamsTab';
import { ExamRoomWorkspace } from './components/ExamRoomWorkspace';
import { NetworkTab } from './components/NetworkTab';
import { EmailDomainsTab, MyAccountTab } from './components/AccountsTab';
import { ChatWidget } from './components/ChatWidget';
import { StaffChatSocket } from './hooks/useStaffChatSocket';
import { ClassWorkspace } from './components/ClassWorkspace';
import { NavHistoryBar, useRoute } from './components/NavHistoryBar';
import { goBack, navigate, parseRoute, pushNav, TAB_LABELS, type TabId } from './navigation';
import { useAuth } from './auth/AuthContext';

const IconDashboard = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" />
    <rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" />
  </svg>
);

const IconClass = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
    <polyline points="9 22 9 12 15 12 15 22" />
  </svg>
);

const IconStudent = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
    <circle cx="9" cy="7" r="4" />
    <path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" />
  </svg>
);

const IconLearning = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" />
    <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" />
  </svg>
);

const IconExam = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
    <polyline points="14 2 14 8 20 8" />
    <line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" />
  </svg>
);

const IconNetwork = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 12.55a11 11 0 0 1 14.08 0" />
    <path d="M1.42 9a16 16 0 0 1 21.16 0" />
    <path d="M8.53 16.11a6 6 0 0 1 6.95 0" />
    <circle cx="12" cy="20" r="1" />
  </svg>
);

const IconEmail = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="2" y="4" width="20" height="16" rx="2" />
    <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
  </svg>
);

function App() {
  const route = useRoute();
  const { staff, logout } = useAuth();

  useEffect(() => {
    const initial = parseRoute();
    if (initial.classId || initial.examId) {
      return;
    }
    pushNav({ kind: 'tab', tab: initial.tab, label: TAB_LABELS[initial.tab] });
  }, []);

  const setActiveTab = (tab: string) => {
    navigate(tab as TabId);
  };

  const handleBackFromWorkspace = () => {
    goBack(route.tab);
  };

  const inWorkspace = Boolean(route.classId || route.examId);

  return (
    <>
      <aside className="sidebar">
        <div className="brand">
          <img src="/logo.jpeg" alt="Simple Care" className="brand-logo-img" />
          <div className="brand-text">
            <span className="brand-name">Simple Care</span>
            <span className="brand-sub">Rikkei Education</span>
          </div>
        </div>

        <nav>
          <ul className="nav-links">
            <div className="nav-header">Tổng quan</div>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'dashboard' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('dashboard')}
              >
                <span className="nav-icon"><IconDashboard /></span>
                Tổng quan
              </button>
            </li>

            <div className="nav-header">CSDL liên kết</div>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'classes' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('classes')}
              >
                <span className="nav-icon"><IconClass /></span>
                Lớp học
              </button>
            </li>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'students' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('students')}
              >
                <span className="nav-icon"><IconStudent /></span>
                Sinh viên
              </button>
            </li>

            <div className="nav-header">Quản lý học tập</div>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'learning' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('learning')}
              >
                <span className="nav-icon"><IconLearning /></span>
                Giám sát & Lịch học
              </button>
            </li>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'exams' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('exams')}
              >
                <span className="nav-icon"><IconExam /></span>
                Phòng thi
              </button>
            </li>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'network' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('network')}
              >
                <span className="nav-icon"><IconNetwork /></span>
                Quản lý mạng
              </button>
            </li>

            <div className="nav-header">Hệ thống</div>
            <li className="nav-item">
              <button
                className={`nav-btn ${route.tab === 'email-domains' && !inWorkspace ? 'active' : ''}`}
                onClick={() => navigate('email-domains')}
              >
                <span className="nav-icon"><IconEmail /></span>
                Đuôi email
              </button>
            </li>
          </ul>
        </nav>

        <div className="sidebar-footer">
          <button
            type="button"
            className={`sidebar-user-btn ${route.tab === 'profile' && !inWorkspace ? 'active' : ''}`}
            onClick={() => navigate('profile')}
            title="Tài khoản của tôi"
          >
            <span className="sidebar-user-name">
              {staff?.fullName?.trim() || staff?.email?.split('@')[0] || 'Tài khoản'}
            </span>
            <span className="sidebar-user-email">{staff?.email}</span>
          </button>
          <button type="button" className="link-btn" onClick={logout}>
            Đăng xuất
          </button>
        </div>
      </aside>

      <main className="main-content">
        <div className="page-viewport">
          {route.classId ? (
            <ClassWorkspace
              classId={route.classId}
              sourceTab={route.tab}
              onBack={handleBackFromWorkspace}
              renderNavBar={(className) => (
                <NavHistoryBar classLabel={className} onBack={handleBackFromWorkspace} />
              )}
            />
          ) : route.examId ? (
            <ExamRoomWorkspace examId={route.examId} onBack={handleBackFromWorkspace} />
          ) : (
            <>
              {route.tab === 'dashboard' && <DashboardTab onNavigate={setActiveTab} />}
              {route.tab === 'classes' && <ClassesTab />}
              {route.tab === 'students' && <StudentsTab />}
              {route.tab === 'learning' && <LearningTab />}
              {route.tab === 'exams' && <ExamsTab />}
              {route.tab === 'network' && <NetworkTab />}
              {route.tab === 'email-domains' && <EmailDomainsTab />}
              {route.tab === 'profile' && <MyAccountTab />}
            </>
          )}
        </div>
      </main>
      <StaffChatSocket />
      <ChatWidget />
    </>
  );
}

export default App;
