'use client';

import { useEffect, useState } from 'react';
import useAlgebraStudent from '@/hooks/useAlgebraStudent';
import { dashboardApi } from '@/api/dashboardClient';
import { UNITS } from '@/components/algebra-dashboard/syllabusData';
import AlgebraDashNav from '@/components/algebra-dashboard/AlgebraDashNav';
import AlgebraOverviewTab from '@/components/algebra-dashboard/AlgebraOverviewTab';
import AlgebraSyllabusTab from '@/components/algebra-dashboard/AlgebraSyllabusTab';
import AlgebraPracticeTab from '@/components/algebra-dashboard/AlgebraPracticeTab';
import AlgebraHomeworkTab from '@/components/algebra-dashboard/AlgebraHomeworkTab';
import AlgebraFeedbackTab from '@/components/algebra-dashboard/AlgebraFeedbackTab';
import AlgebraNotesTab from '@/components/algebra-dashboard/AlgebraNotesTab';
import AlgebraReportTab from '@/components/algebra-dashboard/AlgebraReportTab';
import AlgebraProfilePanel from '@/components/algebra-dashboard/AlgebraProfilePanel';
import AlgebraFooter from '@/components/algebra-dashboard/AlgebraFooter';

export default function AlgebraDashboardClient() {
  const [activeTab, setActiveTab] = useState('overview');
  const [profileOpen, setProfileOpen] = useState(false);
  const [unitNum, setUnitNum] = useState(null);
  const { student, loading, error, refresh } = useAlgebraStudent();

  useEffect(() => {
    if (!student) return;

    let cancelled = false;

    Promise.all([
      dashboardApi.entities.AlgebraExercise.listAll(),
      dashboardApi.entities.AlgebraQuizAttempt.filterAll({ student_id: student.id }),
    ])
      .then(([exercises, attempts]) => {
        if (cancelled) return;
        const done = new Set(attempts.map((attempt) => attempt.exercise_title));
        const current = UNITS.find((unit) => {
          const unitExercises = exercises.filter((exercise) => exercise.unit_id === unit.id);
          return unitExercises.length > 0 && !unitExercises.every((exercise) => done.has(exercise.title));
        });
        setUnitNum(current?.num || null);
      })
      .catch(() => {
        if (!cancelled) setUnitNum(null);
      });

    return () => {
      cancelled = true;
    };
  }, [student, activeTab]);

  const changeTab = (tab) => {
    setProfileOpen(false);
    setActiveTab(tab);
  };

  return (
    <div
      className="min-h-screen flex flex-col"
      style={{ background: '#FAF6EF', fontFamily: "'Axiforma', Arial, Helvetica, sans-serif" }}
    >
      <AlgebraDashNav
        student={student}
        unitNum={student ? unitNum : null}
        activeTab={activeTab}
        onTabChange={changeTab}
        onProfile={() => {
          setProfileOpen(true);
          setActiveTab(null);
        }}
      />

      <main className="flex-1 w-full max-w-6xl mx-auto px-4 sm:px-6 py-6">
        {loading ? (
          <div className="py-24 flex justify-center" role="status" aria-label="Loading dashboard">
            <div
              className="w-8 h-8 border-4 rounded-full animate-spin"
              style={{ borderColor: 'rgba(212,175,56,0.3)', borderTopColor: '#731F32' }}
            />
          </div>
        ) : error ? (<div role="alert" className="p-6 text-sm text-red-700">{error} <button onClick={refresh}>Retry loading dashboard</button></div>) : profileOpen ? (
          <AlgebraProfilePanel
            student={student}
            onSaved={refresh}
            onBack={() => changeTab('overview')}
          />
        ) : !student ? (
          <p className="text-sm font-medium text-center py-24" style={{ color: '#6B5B4E' }}>
            No student record yet — the teacher will add one shortly.
          </p>
        ) : (
          <>
            {activeTab === 'overview' && (
              <AlgebraOverviewTab
                student={student}
                onOpenHomework={() => changeTab('homework')}
                onOpenPractice={() => changeTab('practice')}
                onOpenFeedback={() => changeTab('feedback')}
              />
            )}
            {activeTab === 'syllabus' && <AlgebraSyllabusTab student={student} />}
            {activeTab === 'practice' && <AlgebraPracticeTab student={student} />}
            {activeTab === 'homework' && <AlgebraHomeworkTab student={student} />}
            {activeTab === 'feedback' && (
              <AlgebraFeedbackTab student={student} onOpenPractice={() => changeTab('practice')} />
            )}
            {activeTab === 'notes' && <AlgebraNotesTab student={student} />}
            {activeTab === 'report' && <AlgebraReportTab student={student} />}
          </>
        )}
      </main>

      <AlgebraFooter />
    </div>
  );
}
