'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Progress } from '@/components/ui/progress';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
import {
  GraduationCap,
  Plus,
  Trash2,
  ChevronRight,
  BookOpen,
  Layers,
  HelpCircle,
  FileUp,
  Search,
  Loader2,
  CheckCircle2,
  XCircle,
  AlertCircle,
  FileText,
  Eye,
  Pencil,
  Save,
  Upload,
  Sparkles,
  FolderOpen,
  BookMarked,
  Hash,
} from 'lucide-react';

// ─── Types ───────────────────────────────────────────────────────────────────

interface McqClassData {
  id: string;
  name: string;
  nameBn?: string;
  description?: string;
  order: number;
  isActive: boolean;
  subjectCount?: number;
  questionCount?: number;
  _count?: { subjects: number; questions: number };
}

interface McqSubjectData {
  id: string;
  name: string;
  nameBn?: string;
  description?: string;
  icon?: string;
  classId: string;
  order: number;
  isActive: boolean;
  topicCount?: number;
  questionCount?: number;
  _count?: { topics: number; questions: number };
}

interface McqTopicData {
  id: string;
  name: string;
  nameBn?: string;
  description?: string;
  subjectId: string;
  order: number;
  isActive: boolean;
  questionCount?: number;
  _count?: { questions: number };
}

interface McqQuestionData {
  id: string;
  question: string;
  questionImage?: string;
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  correctAnswer: string;
  difficulty: string;
  explanation?: string;
  classId?: string;
  subjectId?: string;
  topicId?: string;
  category?: string;
  mcqClass?: { id: string; name: string; nameBn?: string };
  subject?: { id: string; name: string; nameBn?: string };
  mcqTopic?: { id: string; name: string; nameBn?: string };
}

interface ExtractedQuestion {
  question: string;
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  correctAnswer: string;
  explanation: string;
  difficulty: string;
  hasImage: boolean;
  classId?: string;
  subjectId?: string;
  topicId?: string;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function adminFetch(url: string, options: RequestInit = {}, token: string | null): Promise<Response> {
  const headers = new Headers(options.headers);
  if (token) headers.set('x-admin-token', token);
  if (!headers.has('Content-Type') && options.body && !(options.body instanceof FormData)) {
    headers.set('Content-Type', 'application/json');
  }
  return fetch(url, { ...options, headers });
}

async function safeJsonParse<T>(response: Response): Promise<T | null> {
  try {
    const text = await response.text();
    if (!text || text.trim().startsWith('<!DOCTYPE') || text.trim().startsWith('<html')) return null;
    return JSON.parse(text) as T;
  } catch {
    return null;
  }
}

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-orange-500 shadow-sm hover:from-orange-700 hover:to-orange-600 text-white';
const ORANGE_OUTLINE = 'border-orange-300 text-orange-600 hover:bg-orange-50 dark:border-orange-700 dark:text-orange-400 dark:hover:bg-orange-950/30';

const EMOJI_OPTIONS = ['📚', '🔢', '🧪', '🌍', '📖', '💻', '🧮', '🔬', '🏛️', '⚡', '🎵', '🎨', '📐', '🧬', '📊'];

// ─── Difficulty Badge ────────────────────────────────────────────────────────

function DifficultyBadge({ difficulty }: { difficulty: string }) {
  const config: Record<string, { label: string; className: string }> = {
    easy: { label: 'Easy', className: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' },
    medium: { label: 'Medium', className: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400' },
    hard: { label: 'Hard', className: 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400' },
  };
  const c = config[difficulty] || config.medium;
  return <Badge className={`text-[10px] border-0 font-medium ${c.className}`}>{c.label}</Badge>;
}

// ─── Main Component ──────────────────────────────────────────────────────────

export default function AdminMCQManager() {
  const { language, adminToken } = useAppStore();
  const isBn = language === 'bn';

  // Navigation levels
  const [selectedClass, setSelectedClass] = useState<McqClassData | null>(null);
  const [selectedSubject, setSelectedSubject] = useState<McqSubjectData | null>(null);
  const [selectedTopic, setSelectedTopic] = useState<McqTopicData | null>(null);

  // Data states
  const [classes, setClasses] = useState<McqClassData[]>([]);
  const [subjects, setSubjects] = useState<McqSubjectData[]>([]);
  const [topics, setTopics] = useState<McqTopicData[]>([]);
  const [questions, setQuestions] = useState<McqQuestionData[]>([]);
  const [loading, setLoading] = useState(true);
  const [questionPagination, setQuestionPagination] = useState({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [questionSearch, setQuestionSearch] = useState('');

  // Dialog states
  const [addClassOpen, setAddClassOpen] = useState(false);
  const [addSubjectOpen, setAddSubjectOpen] = useState(false);
  const [addTopicOpen, setAddTopicOpen] = useState(false);
  const [addMcqOpen, setAddMcqOpen] = useState(false);
  const [uploadPdfOpen, setUploadPdfOpen] = useState(false);
  const [viewMcqOpen, setViewMcqOpen] = useState(false);
  const [viewingMcq, setViewingMcq] = useState<McqQuestionData | null>(null);

  // Submit states
  const [submitting, setSubmitting] = useState(false);

  // ─── Fetch Classes ─────────────────────────────────────────────────────────

  const fetchClasses = useCallback(async () => {
    setLoading(true);
    try {
      const res = await adminFetch('/api/admin/mcq/classes', {}, adminToken);
      const data = await safeJsonParse<{ success: boolean; classes: McqClassData[] }>(res);
      if (data?.success) {
        setClasses(data.classes.map(c => ({
          ...c,
          subjectCount: c._count?.subjects ?? c.subjectCount ?? 0,
          questionCount: c._count?.questions ?? c.questionCount ?? 0,
        })));
      }
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [adminToken]);

  // ─── Fetch Subjects ────────────────────────────────────────────────────────

  const fetchSubjects = useCallback(async (classId: string) => {
    setLoading(true);
    try {
      const res = await adminFetch(`/api/admin/mcq/subjects?classId=${classId}`, {}, adminToken);
      const data = await safeJsonParse<{ success: boolean; subjects: McqSubjectData[] }>(res);
      if (data?.success) {
        setSubjects(data.subjects.map(s => ({
          ...s,
          topicCount: s._count?.topics ?? s.topicCount ?? 0,
          questionCount: s._count?.questions ?? s.questionCount ?? 0,
        })));
      }
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [adminToken]);

  // ─── Fetch Topics ──────────────────────────────────────────────────────────

  const fetchTopics = useCallback(async (subjectId: string) => {
    setLoading(true);
    try {
      const res = await adminFetch(`/api/admin/mcq/topics?subjectId=${subjectId}`, {}, adminToken);
      const data = await safeJsonParse<{ success: boolean; topics: McqTopicData[] }>(res);
      if (data?.success) {
        setTopics(data.topics.map(t => ({
          ...t,
          questionCount: t._count?.questions ?? t.questionCount ?? 0,
        })));
      }
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [adminToken]);

  // ─── Fetch Questions ───────────────────────────────────────────────────────

  const fetchQuestions = useCallback(async (classId?: string, subjectId?: string, topicId?: string, page = 1, search = '') => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (classId) params.set('classId', classId);
      if (subjectId) params.set('subjectId', subjectId);
      if (topicId) params.set('topicId', topicId);
      params.set('page', String(page));
      params.set('limit', '20');
      if (search) params.set('search', search);

      const res = await adminFetch(`/api/admin/mcq?${params.toString()}`, {}, adminToken);
      const data = await safeJsonParse<{
        success: boolean;
        questions: McqQuestionData[];
        pagination: { page: number; limit: number; total: number; totalPages: number };
      }>(res);
      if (data?.success) {
        setQuestions(data.questions);
        setQuestionPagination(data.pagination);
      }
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [adminToken]);

  // ─── Initial Load ──────────────────────────────────────────────────────────

  useEffect(() => {
    if (!selectedClass) {
      fetchClasses();
    }
  }, [selectedClass, fetchClasses]);

  // ─── Navigation handlers ───────────────────────────────────────────────────

  const handleSelectClass = (cls: McqClassData) => {
    setSelectedClass(cls);
    setSelectedSubject(null);
    setSelectedTopic(null);
    setSubjects([]);
    setTopics([]);
    setQuestions([]);
    fetchSubjects(cls.id);
  };

  const handleSelectSubject = (sub: McqSubjectData) => {
    setSelectedSubject(sub);
    setSelectedTopic(null);
    setTopics([]);
    setQuestions([]);
    fetchTopics(sub.id);
  };

  const handleSelectTopic = (topic: McqTopicData) => {
    setSelectedTopic(topic);
    setQuestions([]);
    fetchQuestions(selectedClass?.id, selectedSubject?.id, topic.id);
  };

  const navigateBack = (level: 'classes' | 'subjects' | 'topics') => {
    if (level === 'classes') {
      setSelectedClass(null);
      setSelectedSubject(null);
      setSelectedTopic(null);
      setSubjects([]);
      setTopics([]);
      setQuestions([]);
      fetchClasses();
    } else if (level === 'subjects') {
      setSelectedSubject(null);
      setSelectedTopic(null);
      setTopics([]);
      setQuestions([]);
      if (selectedClass) fetchSubjects(selectedClass.id);
    } else if (level === 'topics') {
      setSelectedTopic(null);
      setQuestions([]);
      if (selectedSubject) fetchTopics(selectedSubject.id);
    }
  };

  // ─── Delete handlers ───────────────────────────────────────────────────────

  const handleDeleteQuestion = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/mcq', {
        method: 'DELETE',
        body: JSON.stringify({ id }),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        fetchQuestions(selectedClass?.id, selectedSubject?.id, selectedTopic?.id, questionPagination.page, questionSearch);
      }
    } catch { /* ignore */ }
  };

  // ─── Breadcrumb ────────────────────────────────────────────────────────────

  const renderBreadcrumb = () => (
    <Breadcrumb className="mb-4">
      <BreadcrumbList>
        <BreadcrumbItem>
          {selectedClass ? (
            <BreadcrumbLink className="cursor-pointer" onClick={() => navigateBack('classes')}>
              <Layers className="mr-1 inline h-3.5 w-3.5" />
              {isBn ? 'ক্লাসসমূহ' : 'Classes'}
            </BreadcrumbLink>
          ) : (
            <BreadcrumbPage>
              <Layers className="mr-1 inline h-3.5 w-3.5" />
              {isBn ? 'ক্লাসসমূহ' : 'Classes'}
            </BreadcrumbPage>
          )}
        </BreadcrumbItem>

        {selectedClass && (
          <>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              {selectedSubject ? (
                <BreadcrumbLink className="cursor-pointer" onClick={() => navigateBack('subjects')}>
                  {selectedClass.nameBn && isBn ? selectedClass.nameBn : selectedClass.name}
                </BreadcrumbLink>
              ) : (
                <BreadcrumbPage>
                  {selectedClass.nameBn && isBn ? selectedClass.nameBn : selectedClass.name}
                </BreadcrumbPage>
              )}
            </BreadcrumbItem>
          </>
        )}

        {selectedSubject && (
          <>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              {selectedTopic ? (
                <BreadcrumbLink className="cursor-pointer" onClick={() => navigateBack('topics')}>
                  {selectedSubject.nameBn && isBn ? selectedSubject.nameBn : selectedSubject.name}
                </BreadcrumbLink>
              ) : (
                <BreadcrumbPage>
                  {selectedSubject.nameBn && isBn ? selectedSubject.nameBn : selectedSubject.name}
                </BreadcrumbPage>
              )}
            </BreadcrumbItem>
          </>
        )}

        {selectedTopic && (
          <>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>
                {selectedTopic.nameBn && isBn ? selectedTopic.nameBn : selectedTopic.name}
              </BreadcrumbPage>
            </BreadcrumbItem>
          </>
        )}
      </BreadcrumbList>
    </Breadcrumb>
  );

  // ─── Loading Spinner ───────────────────────────────────────────────────────

  if (loading && !selectedClass && classes.length === 0) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" />
      </div>
    );
  }

  // ─── Render ────────────────────────────────────────────────────────────────

  return (
    <div className="space-y-4">
      {renderBreadcrumb()}

      {/* Level 1: Classes */}
      {!selectedClass && (
        <ClassesView
          classes={classes}
          language={language}
          onSelect={handleSelectClass}
          onAdd={() => setAddClassOpen(true)}
          loading={loading}
        />
      )}

      {/* Level 2: Subjects */}
      {selectedClass && !selectedSubject && (
        <SubjectsView
          subjects={subjects}
          language={language}
          parentClass={selectedClass}
          onSelect={handleSelectSubject}
          onAdd={() => setAddSubjectOpen(true)}
          loading={loading}
        />
      )}

      {/* Level 3: Topics */}
      {selectedSubject && !selectedTopic && (
        <TopicsView
          topics={topics}
          language={language}
          parentSubject={selectedSubject}
          onSelect={handleSelectTopic}
          onAdd={() => setAddTopicOpen(true)}
          loading={loading}
        />
      )}

      {/* Level 4: MCQs */}
      {selectedTopic && (
        <MCQsView
          questions={questions}
          pagination={questionPagination}
          search={questionSearch}
          language={language}
          parentTopic={selectedTopic}
          parentSubject={selectedSubject}
          parentClass={selectedClass}
          loading={loading}
          onSearchChange={setQuestionSearch}
          onSearchSubmit={() => fetchQuestions(selectedClass?.id, selectedSubject?.id, selectedTopic?.id, 1, questionSearch)}
          onPageChange={(p) => fetchQuestions(selectedClass?.id, selectedSubject?.id, selectedTopic?.id, p, questionSearch)}
          onAddMcq={() => setAddMcqOpen(true)}
          onUploadPdf={() => setUploadPdfOpen(true)}
          onDelete={handleDeleteQuestion}
          onView={(q) => { setViewingMcq(q); setViewMcqOpen(true); }}
        />
      )}

      {/* Dialogs */}
      <AddClassDialog
        open={addClassOpen}
        onOpenChange={setAddClassOpen}
        language={language}
        adminToken={adminToken}
        onSuccess={fetchClasses}
        submitting={submitting}
        setSubmitting={setSubmitting}
      />

      <AddSubjectDialog
        open={addSubjectOpen}
        onOpenChange={setAddSubjectOpen}
        language={language}
        adminToken={adminToken}
        classId={selectedClass?.id || ''}
        onSuccess={() => selectedClass && fetchSubjects(selectedClass.id)}
        submitting={submitting}
        setSubmitting={setSubmitting}
      />

      <AddTopicDialog
        open={addTopicOpen}
        onOpenChange={setAddTopicOpen}
        language={language}
        adminToken={adminToken}
        subjectId={selectedSubject?.id || ''}
        onSuccess={() => selectedSubject && fetchTopics(selectedSubject.id)}
        submitting={submitting}
        setSubmitting={setSubmitting}
      />

      <AddMCQDialog
        open={addMcqOpen}
        onOpenChange={setAddMcqOpen}
        language={language}
        adminToken={adminToken}
        classId={selectedClass?.id}
        subjectId={selectedSubject?.id}
        topicId={selectedTopic?.id}
        onSuccess={() => fetchQuestions(selectedClass?.id, selectedSubject?.id, selectedTopic?.id, questionPagination.page, questionSearch)}
        submitting={submitting}
        setSubmitting={setSubmitting}
      />

      <UploadPdfDialog
        open={uploadPdfOpen}
        onOpenChange={setUploadPdfOpen}
        language={language}
        adminToken={adminToken}
        classId={selectedClass?.id}
        subjectId={selectedSubject?.id}
        topicId={selectedTopic?.id}
        onSuccess={() => fetchQuestions(selectedClass?.id, selectedSubject?.id, selectedTopic?.id, questionPagination.page, questionSearch)}
      />

      <ViewMCQDialog
        open={viewMcqOpen}
        onOpenChange={setViewMcqOpen}
        question={viewingMcq}
        language={language}
      />
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// LEVEL 1 — CLASSES VIEW
// ═════════════════════════════════════════════════════════════════════════════

function ClassesView({
  classes,
  language,
  onSelect,
  onAdd,
  loading,
}: {
  classes: McqClassData[];
  language: string;
  onSelect: (cls: McqClassData) => void;
  onAdd: () => void;
  loading: boolean;
}) {
  const isBn = language === 'bn';

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-foreground">
            {isBn ? 'ক্লাস ক্যাটেগরি' : 'Class Categories'}
          </h2>
          <p className="text-sm text-muted-foreground">
            {isBn ? `${classes.length}টি ক্লাস` : `${classes.length} classes`}
          </p>
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={onAdd}>
          <Plus className="h-4 w-4" />
          {isBn ? 'ক্লাস যোগ করুন' : 'Add Class'}
        </Button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16">
          <span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" />
        </div>
      ) : classes.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-orange-100 dark:bg-orange-950/30">
            <GraduationCap className="h-8 w-8 text-orange-500" strokeWidth={1.5} />
          </div>
          <p className="mt-4 text-sm font-medium text-muted-foreground">
            {isBn ? 'কোনো ক্লাস পাওয়া যায়নি' : 'No classes found'}
          </p>
          <p className="text-xs text-muted-foreground/60">
            {isBn ? 'প্রথম ক্লাস যোগ করুন' : 'Add your first class to get started'}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {classes.map((cls) => (
            <Card
              key={cls.id}
              className="group cursor-pointer overflow-hidden border-0 shadow-sm transition-all hover:shadow-md hover:-translate-y-0.5"
              onClick={() => onSelect(cls)}
            >
              <div className="h-1.5 bg-gradient-to-r from-orange-600 to-amber-500" />
              <CardContent className="p-5">
                <div className="flex items-start gap-3">
                  <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-orange-100 dark:bg-orange-950/30">
                    <GraduationCap className="h-5 w-5 text-orange-600 dark:text-orange-400" strokeWidth={1.75} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="truncate text-sm font-semibold text-foreground">
                      {cls.nameBn && isBn ? cls.nameBn : cls.name}
                    </h3>
                    {cls.description && (
                      <p className="mt-0.5 truncate text-xs text-muted-foreground">{cls.description}</p>
                    )}
                  </div>
                  <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-orange-500" />
                </div>
                <div className="mt-4 flex items-center gap-3">
                  <div className="flex items-center gap-1.5 rounded-lg bg-orange-50 px-2.5 py-1 dark:bg-orange-950/20">
                    <BookOpen className="h-3.5 w-3.5 text-orange-500" />
                    <span className="text-xs font-medium text-orange-700 dark:text-orange-400">
                      {cls.subjectCount ?? 0} {isBn ? 'বিষয়' : 'subjects'}
                    </span>
                  </div>
                  <div className="flex items-center gap-1.5 rounded-lg bg-amber-50 px-2.5 py-1 dark:bg-amber-950/20">
                    <HelpCircle className="h-3.5 w-3.5 text-amber-500" />
                    <span className="text-xs font-medium text-amber-700 dark:text-amber-400">
                      {cls.questionCount ?? 0} {isBn ? 'প্রশ্ন' : 'questions'}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// LEVEL 2 — SUBJECTS VIEW
// ═════════════════════════════════════════════════════════════════════════════

function SubjectsView({
  subjects,
  language,
  parentClass,
  onSelect,
  onAdd,
  loading,
}: {
  subjects: McqSubjectData[];
  language: string;
  parentClass: McqClassData;
  onSelect: (sub: McqSubjectData) => void;
  onAdd: () => void;
  loading: boolean;
}) {
  const isBn = language === 'bn';

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-foreground">
            {isBn ? `${parentClass.nameBn || parentClass.name} - বিষয়সমূহ` : `${parentClass.name} — Subjects`}
          </h2>
          <p className="text-sm text-muted-foreground">
            {isBn ? `${subjects.length}টি বিষয়` : `${subjects.length} subjects`}
          </p>
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={onAdd}>
          <Plus className="h-4 w-4" />
          {isBn ? 'বিষয় যোগ করুন' : 'Add Subject'}
        </Button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16">
          <span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" />
        </div>
      ) : subjects.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-orange-100 dark:bg-orange-950/30">
            <BookOpen className="h-8 w-8 text-orange-500" strokeWidth={1.5} />
          </div>
          <p className="mt-4 text-sm font-medium text-muted-foreground">
            {isBn ? 'কোনো বিষয় পাওয়া যায়নি' : 'No subjects found'}
          </p>
          <p className="text-xs text-muted-foreground/60">
            {isBn ? 'এই ক্লাসে প্রথম বিষয় যোগ করুন' : 'Add the first subject to this class'}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {subjects.map((sub) => (
            <Card
              key={sub.id}
              className="group cursor-pointer overflow-hidden border-0 shadow-sm transition-all hover:shadow-md hover:-translate-y-0.5"
              onClick={() => onSelect(sub)}
            >
              <div className="h-1.5 bg-gradient-to-r from-orange-500 to-amber-400" />
              <CardContent className="p-5">
                <div className="flex items-start gap-3">
                  <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-orange-100 text-xl dark:bg-orange-950/30">
                    {sub.icon || <BookMarked className="h-5 w-5 text-orange-600 dark:text-orange-400" strokeWidth={1.75} />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="truncate text-sm font-semibold text-foreground">
                      {sub.nameBn && isBn ? sub.nameBn : sub.name}
                    </h3>
                    {sub.description && (
                      <p className="mt-0.5 truncate text-xs text-muted-foreground">{sub.description}</p>
                    )}
                  </div>
                  <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-orange-500" />
                </div>
                <div className="mt-4 flex items-center gap-3">
                  <div className="flex items-center gap-1.5 rounded-lg bg-orange-50 px-2.5 py-1 dark:bg-orange-950/20">
                    <Layers className="h-3.5 w-3.5 text-orange-500" />
                    <span className="text-xs font-medium text-orange-700 dark:text-orange-400">
                      {sub.topicCount ?? 0} {isBn ? 'টপিক' : 'topics'}
                    </span>
                  </div>
                  <div className="flex items-center gap-1.5 rounded-lg bg-amber-50 px-2.5 py-1 dark:bg-amber-950/20">
                    <HelpCircle className="h-3.5 w-3.5 text-amber-500" />
                    <span className="text-xs font-medium text-amber-700 dark:text-amber-400">
                      {sub.questionCount ?? 0} {isBn ? 'প্রশ্ন' : 'Qs'}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// LEVEL 3 — TOPICS VIEW
// ═════════════════════════════════════════════════════════════════════════════

function TopicsView({
  topics,
  language,
  parentSubject,
  onSelect,
  onAdd,
  loading,
}: {
  topics: McqTopicData[];
  language: string;
  parentSubject: McqSubjectData;
  onSelect: (topic: McqTopicData) => void;
  onAdd: () => void;
  loading: boolean;
}) {
  const isBn = language === 'bn';

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-foreground">
            {isBn ? `${parentSubject.nameBn || parentSubject.name} - টপিকসমূহ` : `${parentSubject.name} — Topics`}
          </h2>
          <p className="text-sm text-muted-foreground">
            {isBn ? `${topics.length}টি টপিক` : `${topics.length} topics`}
          </p>
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={onAdd}>
          <Plus className="h-4 w-4" />
          {isBn ? 'টপিক যোগ করুন' : 'Add Topic'}
        </Button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16">
          <span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" />
        </div>
      ) : topics.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-orange-100 dark:bg-orange-950/30">
            <FolderOpen className="h-8 w-8 text-orange-500" strokeWidth={1.5} />
          </div>
          <p className="mt-4 text-sm font-medium text-muted-foreground">
            {isBn ? 'কোনো টপিক পাওয়া যায়নি' : 'No topics found'}
          </p>
          <p className="text-xs text-muted-foreground/60">
            {isBn ? 'এই বিষয়ে প্রথম টপিক যোগ করুন' : 'Add the first topic to this subject'}
          </p>
        </div>
      ) : (
        <div className="grid gap-3 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
          {topics.map((topic) => (
            <Card
              key={topic.id}
              className="group cursor-pointer overflow-hidden border-0 shadow-sm transition-all hover:shadow-md hover:-translate-y-0.5"
              onClick={() => onSelect(topic)}
            >
              <div className="h-1 bg-gradient-to-r from-orange-400 to-amber-300" />
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-orange-100 dark:bg-orange-950/30">
                    <Hash className="h-4 w-4 text-orange-600 dark:text-orange-400" strokeWidth={2} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="truncate text-sm font-semibold text-foreground">
                      {topic.nameBn && isBn ? topic.nameBn : topic.name}
                    </h3>
                    <span className="text-xs text-muted-foreground">
                      {topic.questionCount ?? 0} {isBn ? 'প্রশ্ন' : 'questions'}
                    </span>
                  </div>
                  <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-orange-500" />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// LEVEL 4 — MCQS VIEW
// ═════════════════════════════════════════════════════════════════════════════

function MCQsView({
  questions,
  pagination,
  search,
  language,
  parentTopic,
  parentSubject,
  parentClass,
  loading,
  onSearchChange,
  onSearchSubmit,
  onPageChange,
  onAddMcq,
  onUploadPdf,
  onDelete,
  onView,
}: {
  questions: McqQuestionData[];
  pagination: { page: number; limit: number; total: number; totalPages: number };
  search: string;
  language: string;
  parentTopic: McqTopicData;
  parentSubject: McqSubjectData | null;
  parentClass: McqClassData | null;
  loading: boolean;
  onSearchChange: (s: string) => void;
  onSearchSubmit: () => void;
  onPageChange: (p: number) => void;
  onAddMcq: () => void;
  onUploadPdf: () => void;
  onDelete: (id: string) => void;
  onView: (q: McqQuestionData) => void;
}) {
  const isBn = language === 'bn';
  const [deleteTarget, setDeleteTarget] = useState<string | null>(null);

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h2 className="text-lg font-bold text-foreground">
            {isBn ? `${parentTopic.nameBn || parentTopic.name} - প্রশ্নাবলী` : `${parentTopic.name} — Questions`}
          </h2>
          <p className="text-sm text-muted-foreground">
            {isBn ? `মোট ${pagination.total}টি প্রশ্ন` : `${pagination.total} questions total`}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" className={`gap-2 ${ORANGE_OUTLINE}`} onClick={onUploadPdf}>
            <FileUp className="h-4 w-4" />
            <span className="hidden sm:inline">{isBn ? 'PDF আপলোড' : 'Upload PDF'}</span>
          </Button>
          <Button className={`gap-2 ${ORANGE_BTN}`} onClick={onAddMcq}>
            <Plus className="h-4 w-4" />
            {isBn ? 'প্রশ্ন যোগ করুন' : 'Add MCQ'}
          </Button>
        </div>
      </div>

      {/* Search Bar */}
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={isBn ? 'প্রশ্ন খুঁজুন...' : 'Search questions...'}
            value={search}
            onChange={(e) => onSearchChange(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && onSearchSubmit()}
            className="pl-9"
          />
        </div>
        <Button variant="outline" onClick={onSearchSubmit}>
          <Search className="h-4 w-4" />
        </Button>
      </div>

      {/* Questions List */}
      {loading ? (
        <div className="flex items-center justify-center py-16">
          <span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" />
        </div>
      ) : questions.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-orange-100 dark:bg-orange-950/30">
            <HelpCircle className="h-8 w-8 text-orange-500" strokeWidth={1.5} />
          </div>
          <p className="mt-4 text-sm font-medium text-muted-foreground">
            {isBn ? 'কোনো প্রশ্ন পাওয়া যায়নি' : 'No questions found'}
          </p>
          <p className="text-xs text-muted-foreground/60">
            {isBn ? 'ম্যানুয়ালি যোগ করুন অথবা PDF থেকে এক্সট্র্যাক্ট করুন' : 'Add manually or extract from PDF'}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {questions.map((q) => (
            <Card key={q.id} className="overflow-hidden border-0 shadow-sm">
              <CardContent className="p-4">
                <div className="flex items-start gap-3">
                  <div className="flex-1 min-w-0">
                    {/* Question header */}
                    <div className="flex items-center gap-2 mb-2">
                      <DifficultyBadge difficulty={q.difficulty} />
                      {q.category && (
                        <Badge className="bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400 text-[10px] border-0">
                          {q.category}
                        </Badge>
                      )}
                    </div>

                    {/* Question text */}
                    <p className="text-sm font-medium leading-relaxed line-clamp-2">{q.question}</p>

                    {/* Options grid */}
                    <div className="mt-3 grid grid-cols-2 gap-1.5">
                      {(['A', 'B', 'C', 'D'] as const).map((letter) => {
                        const optionKey = `option${letter}` as keyof McqQuestionData;
                        const isCorrect = q.correctAnswer === letter;
                        return (
                          <span
                            key={letter}
                            className={`rounded-lg px-2.5 py-1.5 text-xs ${
                              isCorrect
                                ? 'bg-emerald-50 text-emerald-700 font-semibold dark:bg-emerald-950/30 dark:text-emerald-400 ring-1 ring-emerald-200 dark:ring-emerald-800'
                                : 'bg-slate-50 text-slate-600 dark:bg-slate-800 dark:text-slate-400'
                            }`}
                          >
                            {letter}. {q[optionKey] as string}
                          </span>
                        );
                      })}
                    </div>

                    {/* Explanation preview */}
                    {q.explanation && (
                      <p className="mt-2 text-xs text-muted-foreground line-clamp-1">
                        💡 {q.explanation}
                      </p>
                    )}
                  </div>

                  {/* Actions */}
                  <div className="flex flex-col gap-1 shrink-0">
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => onView(q)}>
                      <Eye className="h-3.5 w-3.5 text-muted-foreground" />
                    </Button>
                    <AlertDialog open={deleteTarget === q.id} onOpenChange={(open) => !open && setDeleteTarget(null)}>
                      <AlertDialogTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setDeleteTarget(q.id)}>
                          <Trash2 className="h-3.5 w-3.5 text-destructive" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>{isBn ? 'প্রশ্ন মুছুন' : 'Delete Question'}</AlertDialogTitle>
                          <AlertDialogDescription>
                            {isBn ? 'এই প্রশ্নটি মুছে ফেলতে চান?' : 'Are you sure you want to delete this question?'}
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>{isBn ? 'বাতিল' : 'Cancel'}</AlertDialogCancel>
                          <AlertDialogAction
                            onClick={() => { onDelete(q.id); setDeleteTarget(null); }}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                          >
                            {isBn ? 'মুছুন' : 'Delete'}
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Pagination */}
      {pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-muted-foreground">
            {isBn
              ? `পৃষ্ঠা ${pagination.page} / ${pagination.totalPages} (মোট ${pagination.total})`
              : `Page ${pagination.page} of ${pagination.totalPages} (${pagination.total} total)`
            }
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={pagination.page <= 1}
              onClick={() => onPageChange(pagination.page - 1)}
            >
              {isBn ? 'আগে' : 'Prev'}
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={pagination.page >= pagination.totalPages}
              onClick={() => onPageChange(pagination.page + 1)}
            >
              {isBn ? 'পরে' : 'Next'}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ADD CLASS DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function AddClassDialog({
  open,
  onOpenChange,
  language,
  adminToken,
  onSuccess,
  submitting,
  setSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  language: string;
  adminToken: string | null;
  onSuccess: () => void;
  submitting: boolean;
  setSubmitting: (s: boolean) => void;
}) {
  const isBn = language === 'bn';
  const [form, setForm] = useState({ name: '', nameBn: '', description: '', order: 0 });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await adminFetch('/api/admin/mcq/classes', {
        method: 'POST',
        body: JSON.stringify(form),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        setForm({ name: '', nameBn: '', description: '', order: 0 });
        onOpenChange(false);
        onSuccess();
      }
    } catch { /* ignore */ }
    finally { setSubmitting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <GraduationCap className="h-5 w-5 text-orange-500" />
            {isBn ? 'নতুন ক্লাস যোগ করুন' : 'Add New Class'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'একটি নতুন ক্লাস ক্যাটেগরি তৈরি করুন' : 'Create a new class category'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 pt-2">
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (ইংরেজি)' : 'Name (English)'} *</Label>
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required placeholder="e.g. Class 9-10" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
            <Input value={form.nameBn} onChange={(e) => setForm({ ...form, nameBn: e.target.value })} placeholder="যেমন: নবম-দশম শ্রেণি" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'বিবরণ' : 'Description'}</Label>
            <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={isBn ? 'ঐচ্ছিক বিবরণ...' : 'Optional description...'} rows={2} />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'ক্রম' : 'Order'}</Label>
            <Input type="number" value={form.order} onChange={(e) => setForm({ ...form, order: parseInt(e.target.value) || 0 })} />
          </div>
          <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={submitting}>
            {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Plus className="mr-2 h-4 w-4" />}
            {isBn ? 'ক্লাস তৈরি করুন' : 'Create Class'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ADD SUBJECT DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function AddSubjectDialog({
  open,
  onOpenChange,
  language,
  adminToken,
  classId,
  onSuccess,
  submitting,
  setSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  language: string;
  adminToken: string | null;
  classId: string;
  onSuccess: () => void;
  submitting: boolean;
  setSubmitting: (s: boolean) => void;
}) {
  const isBn = language === 'bn';
  const [form, setForm] = useState({ name: '', nameBn: '', description: '', icon: '📚', order: 0 });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await adminFetch('/api/admin/mcq/subjects', {
        method: 'POST',
        body: JSON.stringify({ ...form, classId }),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        setForm({ name: '', nameBn: '', description: '', icon: '📚', order: 0 });
        onOpenChange(false);
        onSuccess();
      }
    } catch { /* ignore */ }
    finally { setSubmitting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <BookOpen className="h-5 w-5 text-orange-500" />
            {isBn ? 'নতুন বিষয় যোগ করুন' : 'Add New Subject'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'এই ক্লাসে একটি নতুন বিষয় তৈরি করুন' : 'Create a new subject for this class'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 pt-2">
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (ইংরেজি)' : 'Name (English)'} *</Label>
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required placeholder="e.g. Mathematics" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
            <Input value={form.nameBn} onChange={(e) => setForm({ ...form, nameBn: e.target.value })} placeholder="যেমন: গণিত" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'বিবরণ' : 'Description'}</Label>
            <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={isBn ? 'ঐচ্ছিক বিবরণ...' : 'Optional description...'} rows={2} />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'আইকন' : 'Icon'}</Label>
            <div className="flex flex-wrap gap-2">
              {EMOJI_OPTIONS.map((emoji) => (
                <button
                  key={emoji}
                  type="button"
                  className={`flex h-9 w-9 items-center justify-center rounded-lg text-lg transition-all ${
                    form.icon === emoji
                      ? 'bg-orange-100 ring-2 ring-orange-500 dark:bg-orange-950/30'
                      : 'bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700'
                  }`}
                  onClick={() => setForm({ ...form, icon: emoji })}
                >
                  {emoji}
                </button>
              ))}
            </div>
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'ক্রম' : 'Order'}</Label>
            <Input type="number" value={form.order} onChange={(e) => setForm({ ...form, order: parseInt(e.target.value) || 0 })} />
          </div>
          <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={submitting}>
            {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Plus className="mr-2 h-4 w-4" />}
            {isBn ? 'বিষয় তৈরি করুন' : 'Create Subject'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ADD TOPIC DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function AddTopicDialog({
  open,
  onOpenChange,
  language,
  adminToken,
  subjectId,
  onSuccess,
  submitting,
  setSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  language: string;
  adminToken: string | null;
  subjectId: string;
  onSuccess: () => void;
  submitting: boolean;
  setSubmitting: (s: boolean) => void;
}) {
  const isBn = language === 'bn';
  const [form, setForm] = useState({ name: '', nameBn: '', description: '', order: 0 });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await adminFetch('/api/admin/mcq/topics', {
        method: 'POST',
        body: JSON.stringify({ ...form, subjectId }),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        setForm({ name: '', nameBn: '', description: '', order: 0 });
        onOpenChange(false);
        onSuccess();
      }
    } catch { /* ignore */ }
    finally { setSubmitting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Layers className="h-5 w-5 text-orange-500" />
            {isBn ? 'নতুন টপিক যোগ করুন' : 'Add New Topic'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'এই বিষয়ে একটি নতুন টপিক তৈরি করুন' : 'Create a new topic for this subject'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 pt-2">
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (ইংরেজি)' : 'Name (English)'} *</Label>
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required placeholder="e.g. Algebra" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
            <Input value={form.nameBn} onChange={(e) => setForm({ ...form, nameBn: e.target.value })} placeholder="যেমন: বীজগণিত" />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'বিবরণ' : 'Description'}</Label>
            <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={isBn ? 'ঐচ্ছিক বিবরণ...' : 'Optional description...'} rows={2} />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'ক্রম' : 'Order'}</Label>
            <Input type="number" value={form.order} onChange={(e) => setForm({ ...form, order: parseInt(e.target.value) || 0 })} />
          </div>
          <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={submitting}>
            {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Plus className="mr-2 h-4 w-4" />}
            {isBn ? 'টপিক তৈরি করুন' : 'Create Topic'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ADD MCQ DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function AddMCQDialog({
  open,
  onOpenChange,
  language,
  adminToken,
  classId,
  subjectId,
  topicId,
  onSuccess,
  submitting,
  setSubmitting,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  language: string;
  adminToken: string | null;
  classId?: string;
  subjectId?: string;
  topicId?: string;
  onSuccess: () => void;
  submitting: boolean;
  setSubmitting: (s: boolean) => void;
}) {
  const isBn = language === 'bn';
  const [form, setForm] = useState({
    question: '',
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    correctAnswer: 'A',
    difficulty: 'medium',
    category: 'gk',
    explanation: '',
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await adminFetch('/api/admin/mcq', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          classId: classId || undefined,
          subjectId: subjectId || undefined,
          topicId: topicId || undefined,
        }),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        setForm({
          question: '',
          optionA: '',
          optionB: '',
          optionC: '',
          optionD: '',
          correctAnswer: 'A',
          difficulty: 'medium',
          category: 'gk',
          explanation: '',
        });
        onOpenChange(false);
        onSuccess();
      }
    } catch { /* ignore */ }
    finally { setSubmitting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[560px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <HelpCircle className="h-5 w-5 text-orange-500" />
            {isBn ? 'নতুন MCQ প্রশ্ন যোগ করুন' : 'Add New MCQ Question'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'একটি নতুন বহুনির্বাচনি প্রশ্ন তৈরি করুন' : 'Create a new multiple choice question'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 pt-2">
          {/* Question */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'প্রশ্ন' : 'Question'} *</Label>
            <Textarea
              value={form.question}
              onChange={(e) => setForm({ ...form, question: e.target.value })}
              required
              rows={3}
              placeholder={isBn ? 'প্রশ্ন লিখুন...' : 'Enter question text...'}
            />
          </div>

          {/* Options */}
          <div className="grid grid-cols-2 gap-3">
            {(['A', 'B', 'C', 'D'] as const).map((letter) => (
              <div key={letter} className="space-y-2">
                <Label className="text-xs font-medium">
                  {isBn ? `বিকল্প ${letter}` : `Option ${letter}`} *
                </Label>
                <Input
                  value={form[`option${letter}` as keyof typeof form] as string}
                  onChange={(e) => setForm({ ...form, [`option${letter}`]: e.target.value })}
                  required
                  placeholder={`${letter}.`}
                />
              </div>
            ))}
          </div>

          {/* Correct Answer, Difficulty, Category */}
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-2">
              <Label className="text-xs font-medium">{isBn ? 'সঠিক উত্তর' : 'Correct Answer'}</Label>
              <Select value={form.correctAnswer} onValueChange={(v) => setForm({ ...form, correctAnswer: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="A">A</SelectItem>
                  <SelectItem value="B">B</SelectItem>
                  <SelectItem value="C">C</SelectItem>
                  <SelectItem value="D">D</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label className="text-xs font-medium">{isBn ? 'কঠিনতা' : 'Difficulty'}</Label>
              <Select value={form.difficulty} onValueChange={(v) => setForm({ ...form, difficulty: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="easy">{isBn ? 'সহজ' : 'Easy'}</SelectItem>
                  <SelectItem value="medium">{isBn ? 'মাঝারি' : 'Medium'}</SelectItem>
                  <SelectItem value="hard">{isBn ? 'কঠিন' : 'Hard'}</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label className="text-xs font-medium">{isBn ? 'ক্যাটেগরি' : 'Category'}</Label>
              <Select value={form.category} onValueChange={(v) => setForm({ ...form, category: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="gk">GK</SelectItem>
                  <SelectItem value="math">Math</SelectItem>
                  <SelectItem value="science">Science</SelectItem>
                  <SelectItem value="english">English</SelectItem>
                  <SelectItem value="bangla">Bangla</SelectItem>
                  <SelectItem value="ict">ICT</SelectItem>
                  <SelectItem value="ssc">SSC</SelectItem>
                  <SelectItem value="hsc">HSC</SelectItem>
                  <SelectItem value="admission">Admission</SelectItem>
                  <SelectItem value="bcs">BCS</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Explanation */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">{isBn ? 'ব্যাখ্যা' : 'Explanation'}</Label>
            <Textarea
              value={form.explanation}
              onChange={(e) => setForm({ ...form, explanation: e.target.value })}
              placeholder={isBn ? 'ঐচ্ছিক ব্যাখ্যা...' : 'Optional explanation...'}
              rows={2}
            />
          </div>

          <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={submitting}>
            {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Plus className="mr-2 h-4 w-4" />}
            {isBn ? 'প্রশ্ন যোগ করুন' : 'Add Question'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// UPLOAD PDF DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function UploadPdfDialog({
  open,
  onOpenChange,
  language,
  adminToken,
  classId,
  subjectId,
  topicId,
  onSuccess,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  language: string;
  adminToken: string | null;
  classId?: string;
  subjectId?: string;
  topicId?: string;
  onSuccess: () => void;
}) {
  const isBn = language === 'bn';
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [extracting, setExtracting] = useState(false);
  const [extractedQuestions, setExtractedQuestions] = useState<ExtractedQuestion[]>([]);
  const [extractionInfo, setExtractionInfo] = useState({ totalExtracted: 0, pagesProcessed: 0, errors: [] as string[] });
  const [saving, setSaving] = useState(false);
  const [step, setStep] = useState<'upload' | 'review' | 'done'>('upload');

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) setSelectedFile(file);
  };

  const handleExtract = async () => {
    if (!selectedFile) return;
    setExtracting(true);
    try {
      const formData = new FormData();
      formData.append('file', selectedFile);
      if (classId) formData.append('classId', classId);
      if (subjectId) formData.append('subjectId', subjectId);
      if (topicId) formData.append('topicId', topicId);

      const res = await adminFetch('/api/admin/mcq/extract-pdf', {
        method: 'POST',
        body: formData,
      }, adminToken);

      const data = await safeJsonParse<{
        success: boolean;
        extractedQuestions: ExtractedQuestion[];
        totalExtracted: number;
        pagesProcessed: number;
        errors?: string[];
        message?: string;
      }>(res);

      if (data?.success) {
        setExtractedQuestions(data.extractedQuestions);
        setExtractionInfo({
          totalExtracted: data.totalExtracted,
          pagesProcessed: data.pagesProcessed,
          errors: data.errors || [],
        });
        setStep('review');
      } else {
        // Show error
      }
    } catch { /* ignore */ }
    finally { setExtracting(false); }
  };

  const handleRemoveExtracted = (index: number) => {
    setExtractedQuestions(prev => prev.filter((_, i) => i !== index));
  };

  const handleUpdateExtracted = (index: number, field: string, value: string) => {
    setExtractedQuestions(prev => prev.map((q, i) => i === index ? { ...q, [field]: value } : q));
  };

  const handleSaveAll = async () => {
    if (extractedQuestions.length === 0) return;
    setSaving(true);
    try {
      const res = await adminFetch('/api/admin/mcq/bulk', {
        method: 'POST',
        body: JSON.stringify({
          questions: extractedQuestions,
          classId: classId || undefined,
          subjectId: subjectId || undefined,
          topicId: topicId || undefined,
        }),
      }, adminToken);

      const data = await safeJsonParse<{ success: boolean; created: number }>(res);
      if (data?.success) {
        setStep('done');
        onSuccess();
      }
    } catch { /* ignore */ }
    finally { setSaving(false); }
  };

  const handleReset = () => {
    setSelectedFile(null);
    setExtractedQuestions([]);
    setExtractionInfo({ totalExtracted: 0, pagesProcessed: 0, errors: [] });
    setStep('upload');
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const handleClose = () => {
    handleReset();
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[640px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <FileUp className="h-5 w-5 text-orange-500" />
            {isBn ? 'PDF থেকে MCQ এক্সট্র্যাক্ট করুন' : 'Extract MCQs from PDF'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'একটি PDF আপলোড করুন এবং AI ব্যবহার করে MCQ প্রশ্ন এক্সট্র্যাক্ট করুন' : 'Upload a PDF and use AI to extract MCQ questions'}
          </DialogDescription>
        </DialogHeader>

        {/* Step 1: Upload */}
        {step === 'upload' && (
          <div className="space-y-4 pt-2">
            <div
              className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-orange-300 bg-orange-50/50 p-8 dark:border-orange-700 dark:bg-orange-950/10 cursor-pointer hover:border-orange-400 transition-colors"
              onClick={() => fileInputRef.current?.click()}
            >
              <Upload className="h-10 w-10 text-orange-400 mb-3" strokeWidth={1.5} />
              <p className="text-sm font-medium text-foreground">
                {isBn ? 'PDF ফাইল নির্বাচন করুন' : 'Select PDF file'}
              </p>
              <p className="text-xs text-muted-foreground mt-1">
                {isBn ? 'সর্বোচ্চ ২০MB, ৩০ পৃষ্ঠা পর্যন্ত' : 'Max 20MB, up to 30 pages'}
              </p>
              <input
                ref={fileInputRef}
                type="file"
                accept=".pdf"
                className="hidden"
                onChange={handleFileSelect}
              />
            </div>

            {selectedFile && (
              <div className="flex items-center gap-3 rounded-lg bg-slate-50 p-3 dark:bg-slate-800">
                <FileText className="h-8 w-8 text-orange-500" />
                <div className="flex-1 min-w-0">
                  <p className="truncate text-sm font-medium">{selectedFile.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                  </p>
                </div>
                <CheckCircle2 className="h-5 w-5 text-emerald-500" />
              </div>
            )}

            <Button
              className={`w-full ${ORANGE_BTN} font-semibold`}
              onClick={handleExtract}
              disabled={!selectedFile || extracting}
            >
              {extracting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {isBn ? 'এক্সট্র্যাক্ট হচ্ছে...' : 'Extracting...'}
                </>
              ) : (
                <>
                  <Sparkles className="mr-2 h-4 w-4" />
                  {isBn ? 'MCQ এক্সট্র্যাক্ট করুন' : 'Extract MCQs'}
                </>
              )}
            </Button>
          </div>
        )}

        {/* Step 2: Review */}
        {step === 'review' && (
          <div className="space-y-4 pt-2">
            {/* Extraction Info */}
            <div className="flex items-center gap-3 rounded-lg bg-emerald-50 p-3 dark:bg-emerald-950/20">
              <CheckCircle2 className="h-5 w-5 text-emerald-500 shrink-0" />
              <div className="flex-1">
                <p className="text-sm font-medium text-emerald-700 dark:text-emerald-400">
                  {extractionInfo.totalExtracted} {isBn ? 'টি প্রশ্ন এক্সট্র্যাক্ট হয়েছে' : 'questions extracted'}
                </p>
                <p className="text-xs text-emerald-600/70 dark:text-emerald-400/70">
                  {extractionInfo.pagesProcessed} {isBn ? 'পৃষ্ঠা প্রসেস হয়েছে' : 'pages processed'}
                </p>
              </div>
            </div>

            {extractionInfo.errors.length > 0 && (
              <div className="rounded-lg bg-amber-50 p-3 dark:bg-amber-950/20">
                <div className="flex items-center gap-2 text-amber-700 dark:text-amber-400">
                  <AlertCircle className="h-4 w-4" />
                  <p className="text-xs font-medium">
                    {isBn ? 'কিছু সতর্কতা:' : 'Some warnings:'}
                  </p>
                </div>
                {extractionInfo.errors.map((err, i) => (
                  <p key={i} className="text-xs text-amber-600 dark:text-amber-400/70 ml-6">{err}</p>
                ))}
              </div>
            )}

            <Separator />

            {/* Review List */}
            <div className="space-y-3 max-h-96 overflow-y-auto pr-1">
              {extractedQuestions.map((q, index) => (
                <Card key={index} className="border shadow-none">
                  <CardContent className="p-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-bold text-orange-600">#{index + 1}</span>
                          <DifficultyBadge difficulty={q.difficulty} />
                        </div>
                        <p className="text-sm font-medium line-clamp-2">{q.question}</p>
                        <div className="mt-1.5 grid grid-cols-2 gap-1 text-xs">
                          {(['A', 'B', 'C', 'D'] as const).map((letter) => {
                            const key = `option${letter}` as keyof ExtractedQuestion;
                            const isCorrect = q.correctAnswer === letter;
                            return (
                              <span
                                key={letter}
                                className={`rounded px-1.5 py-0.5 ${
                                  isCorrect
                                    ? 'bg-emerald-50 text-emerald-700 font-semibold dark:bg-emerald-950/30 dark:text-emerald-400'
                                    : 'bg-slate-50 text-slate-600 dark:bg-slate-800 dark:text-slate-400'
                                }`}
                              >
                                {letter}. {q[key] as string}
                              </span>
                            );
                          })}
                        </div>
                      </div>
                      <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => handleRemoveExtracted(index)}>
                        <XCircle className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>

            {extractedQuestions.length === 0 && (
              <div className="py-8 text-center">
                <p className="text-sm text-muted-foreground">
                  {isBn ? 'কোনো প্রশ্ন অবশিষ্ট নেই' : 'No questions remaining'}
                </p>
              </div>
            )}

            {/* Actions */}
            <div className="flex gap-2">
              <Button variant="outline" className="flex-1" onClick={() => setStep('upload')}>
                {isBn ? 'ফিরে যান' : 'Back'}
              </Button>
              <Button
                className={`flex-1 ${ORANGE_BTN} font-semibold`}
                onClick={handleSaveAll}
                disabled={saving || extractedQuestions.length === 0}
              >
                {saving ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Save className="mr-2 h-4 w-4" />
                )}
                {isBn
                  ? `সব সংরক্ষণ করুন (${extractedQuestions.length})`
                  : `Save All (${extractedQuestions.length})`
                }
              </Button>
            </div>
          </div>
        )}

        {/* Step 3: Done */}
        {step === 'done' && (
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-emerald-100 dark:bg-emerald-950/30">
              <CheckCircle2 className="h-8 w-8 text-emerald-500" />
            </div>
            <h3 className="mt-4 text-lg font-semibold">
              {isBn ? 'সফলভাবে সংরক্ষিত!' : 'Successfully Saved!'}
            </h3>
            <p className="mt-1 text-sm text-muted-foreground">
              {isBn
                ? `${extractionInfo.totalExtracted}টি প্রশ্ন সংরক্ষিত হয়েছে`
                : `${extractionInfo.totalExtracted} questions have been saved`
              }
            </p>
            <Button className={`mt-4 ${ORANGE_BTN}`} onClick={handleClose}>
              {isBn ? 'সম্পন্ন' : 'Done'}
            </Button>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// VIEW MCQ DIALOG
// ═════════════════════════════════════════════════════════════════════════════

function ViewMCQDialog({
  open,
  onOpenChange,
  question,
  language,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  question: McqQuestionData | null;
  language: string;
}) {
  const isBn = language === 'bn';

  if (!question) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[520px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Eye className="h-5 w-5 text-orange-500" />
            {isBn ? 'প্রশ্ন বিস্তারিত' : 'Question Detail'}
          </DialogTitle>
          <DialogDescription>
            {isBn ? 'MCQ প্রশ্নের বিস্তারিত দেখুন' : 'View MCQ question details'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 pt-2">
          {/* Badges */}
          <div className="flex items-center gap-2 flex-wrap">
            <DifficultyBadge difficulty={question.difficulty} />
            {question.category && (
              <Badge className="bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400 text-[10px] border-0">
                {question.category}
              </Badge>
            )}
            {question.mcqClass && (
              <Badge variant="outline" className="text-[10px]">
                {question.mcqClass.nameBn && isBn ? question.mcqClass.nameBn : question.mcqClass.name}
              </Badge>
            )}
            {question.subject && (
              <Badge variant="outline" className="text-[10px]">
                {question.subject.nameBn && isBn ? question.subject.nameBn : question.subject.name}
              </Badge>
            )}
            {question.mcqTopic && (
              <Badge variant="outline" className="text-[10px]">
                {question.mcqTopic.nameBn && isBn ? question.mcqTopic.nameBn : question.mcqTopic.name}
              </Badge>
            )}
          </div>

          {/* Question */}
          <div className="rounded-lg bg-slate-50 p-4 dark:bg-slate-800">
            <p className="text-sm font-medium leading-relaxed">{question.question}</p>
          </div>

          {/* Options */}
          <div className="space-y-2">
            {(['A', 'B', 'C', 'D'] as const).map((letter) => {
              const optionKey = `option${letter}` as keyof McqQuestionData;
              const isCorrect = question.correctAnswer === letter;
              return (
                <div
                  key={letter}
                  className={`flex items-center gap-3 rounded-lg border p-3 ${
                    isCorrect
                      ? 'border-emerald-300 bg-emerald-50 dark:border-emerald-700 dark:bg-emerald-950/20'
                      : 'border-border bg-background'
                  }`}
                >
                  <span className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold ${
                    isCorrect
                      ? 'bg-emerald-500 text-white'
                      : 'bg-slate-200 text-slate-600 dark:bg-slate-700 dark:text-slate-300'
                  }`}>
                    {letter}
                  </span>
                  <span className={`text-sm ${isCorrect ? 'font-semibold text-emerald-700 dark:text-emerald-400' : ''}`}>
                    {question[optionKey] as string}
                  </span>
                  {isCorrect && <CheckCircle2 className="ml-auto h-4 w-4 text-emerald-500 shrink-0" />}
                </div>
              );
            })}
          </div>

          {/* Explanation */}
          {question.explanation && (
            <div className="rounded-lg bg-amber-50 p-4 dark:bg-amber-950/20">
              <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 mb-1">
                {isBn ? 'ব্যাখ্যা:' : 'Explanation:'}
              </p>
              <p className="text-sm text-amber-800 dark:text-amber-300">{question.explanation}</p>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
