"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ImportModal } from "@/components/import/ImportModal";
import { ShareMenu } from "@/components/ui/ShareMenu";
import {
  DndContext,
  pointerWithin,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
  DragOverEvent,
  DragStartEvent,
  DragOverlay,
  useDroppable,
  useDndContext,
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
  useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

interface QuizItem {
  id: string;
  name: string;
  description: string | null;
  groupId: string | null;
  sortOrder: number;
  _count: { questions: number; attempts: number };
}

interface MaterialGroup {
  id: string;
  name: string;
  sortOrder: number;
}

const cache: Record<string, { quizzes: QuizItem[]; groups: MaterialGroup[] }> = {};

function SortableQuizCard({ quiz, onEdit, onDelete, classSlug }: any) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: quiz.id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.4 : 1,
  };

  return (
    <div ref={setNodeRef} style={style} className="group rounded-2xl border border-border-light bg-bg-surface shadow-[var(--shadow-card)] transition-all duration-300 hover:-translate-y-0.5 hover:border-primary/25 hover:shadow-[var(--shadow-card-hover)]">
      <div className="flex h-full flex-1 flex-col p-5">
        <div className="flex items-start gap-2">
          <div {...attributes} {...listeners} className="mt-1 cursor-grab active:cursor-grabbing text-text-muted hover:text-text-heading">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8h16M4 16h16" />
            </svg>
          </div>
          <div className="flex-1">
            <h3 className="mb-1 text-lg font-extrabold text-text-heading">{quiz.name}</h3>
            {quiz.description && <p className="text-sm text-text-secondary mb-3 line-clamp-2">{quiz.description}</p>}
          </div>
        </div>

        <div className="flex items-center gap-3 mt-auto pl-7">
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-badge-bg text-badge-text text-xs font-medium">
            {quiz._count.questions} {quiz._count.questions === 1 ? "question" : "questions"}
          </span>
          {quiz._count.attempts > 0 && (
            <span className="text-xs text-text-muted">
              {quiz._count.attempts} {quiz._count.attempts === 1 ? "attempt" : "attempts"}
            </span>
          )}
        </div>

        <div className="flex items-center gap-2 mt-4 pt-4 border-t border-border-light pl-7">
          <Link href={`/${classSlug}/quizzes/${quiz.id}`} className="flex-1 text-center py-2 px-4 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-hover transition-all duration-200">
            Start Quiz
          </Link>
          <button onClick={() => onEdit(quiz)} className="p-2 rounded-lg text-text-muted hover:text-text-heading hover:bg-bg-surface-alt transition-all duration-200 cursor-pointer" title="Edit">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          </button>
          <button onClick={() => onDelete(quiz)} className="p-2 rounded-lg text-text-muted hover:text-error hover:bg-error-bg transition-all duration-200 cursor-pointer" title="Delete">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function DroppableContainer({ id, children }: { id: string; children: React.ReactNode }) {
  const { setNodeRef } = useDroppable({ id });
  const { over } = useDndContext();
  
  const isOverContainer = over?.id === id;
  const isOverChild = over?.data?.current?.sortable?.containerId === id;
  const isOver = isOverContainer || isOverChild;

  return (
    <div ref={setNodeRef} className={`grid grid-cols-1 md:grid-cols-2 gap-4 min-h-[60px] p-2 -mx-2 rounded-lg border-2 transition-colors duration-200 ${isOver ? "border-primary/40 bg-primary/5 shadow-inner" : "border-transparent"}`}>
      {children}
    </div>
  );
}

export default function QuizzesPage() {
  const params = useParams();
  const classSlug = params.classSlug as string;
  const [quizzes, setQuizzes] = useState<QuizItem[]>(cache[classSlug]?.quizzes || []);
  const [groups, setGroups] = useState<MaterialGroup[]>(cache[classSlug]?.groups || []);
  const [loading, setLoading] = useState(!cache[classSlug]);
  const [animate] = useState(!cache[classSlug]);
  const [showImport, setShowImport] = useState(false);
  const [classId, setClassId] = useState<string>("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [editDescription, setEditDescription] = useState("");
  const [isCreatingGroup, setIsCreatingGroup] = useState(false);
  const [newGroupName, setNewGroupName] = useState("");
  const [editingGroupId, setEditingGroupId] = useState<string | null>(null);
  const [editGroupName, setEditGroupName] = useState("");
  const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>({});

  useEffect(() => {
    const saved = localStorage.getItem('quizzes_collapsed_groups');
    if (saved) {
      try { setCollapsedGroups(JSON.parse(saved)); } catch(e) {}
    }
  }, []);

  function toggleGroup(id: string) {
    setCollapsedGroups(prev => {
      const next = { ...prev, [id]: !prev[id] };
      localStorage.setItem('quizzes_collapsed_groups', JSON.stringify(next));
      return next;
    });
  }

  const fetchAll = useCallback(async (cId: string) => {
    try {
      const [quizRes, groupRes] = await Promise.all([
        fetch(`/api/quizzes/list?classId=${cId}`),
        fetch(`/api/material-groups?classId=${cId}&type=QUIZ`),
      ]);
      const qs = quizRes.ok ? await quizRes.json() : [];
      const gs = groupRes.ok ? await groupRes.json() : [];
      setQuizzes(qs);
      setGroups(gs);
      cache[classSlug] = { quizzes: qs, groups: gs };
    } catch {
      setQuizzes([]);
      setGroups([]);
    } finally {
      setLoading(false);
    }
  }, [classSlug]);

  useEffect(() => {
    async function init() {
      try {
        const classRes = await fetch("/api/classes");
        const classes = await classRes.json();
        const cls = classes.find((c: { slug: string }) => c.slug === classSlug);
        if (!cls) {
          setLoading(false);
          return;
        }
        setClassId(cls.id);
        fetchAll(cls.id);
      } catch {
        setLoading(false);
      }
    }
    init();
  }, [classSlug, fetchAll]);

  // Group Management
  async function handleCreateGroup() {
    if (!newGroupName.trim()) return;
    const res = await fetch("/api/material-groups", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ classId, name: newGroupName.trim(), type: "QUIZ" }),
    });
    if (res.ok) {
      const g = await res.json();
      setGroups((prev) => [...prev, g]);
      setIsCreatingGroup(false);
      setNewGroupName("");
    }
  }

  async function handleRenameGroup(id: string) {
    if (!editGroupName.trim()) return;
    await fetch(`/api/material-groups/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: editGroupName.trim() }),
    });
    setGroups((prev) => prev.map((g) => (g.id === id ? { ...g, name: editGroupName.trim() } : g)));
    setEditingGroupId(null);
  }

  async function handleDeleteGroup(id: string, name: string) {
    if (!confirm(`Delete group "${name}"? Quizzes inside will be moved to Uncategorized.`)) return;
    await fetch(`/api/material-groups/${id}`, { method: "DELETE" });
    setGroups((prev) => prev.filter((g) => g.id !== id));
    setQuizzes((prev) => prev.map((q) => (q.groupId === id ? { ...q, groupId: null } : q)));
  }

  // Quiz Management
  async function handleDeleteQuiz(quiz: QuizItem) {
    if (!confirm(`Delete "${quiz.name}" and all its questions and attempts?`)) return;
    await fetch(`/api/quizzes/${quiz.id}`, { method: "DELETE" });
    setQuizzes((prev) => prev.filter((q) => q.id !== quiz.id));
  }

  async function handleRenameQuiz(id: string) {
    if (!editName.trim()) return;
    await fetch(`/api/quizzes/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: editName.trim(), description: editDescription.trim() || null }),
    });
    setQuizzes((prev) =>
      prev.map((q) => (q.id === id ? { ...q, name: editName.trim(), description: editDescription.trim() || null } : q))
    );
    setEditingId(null);
  }

  // Drag and drop setup
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );

  const [activeId, setActiveId] = useState<string | null>(null);

  function handleDragStart(event: DragStartEvent) {
    setActiveId(event.active.id as string);
  }

  function handleDragOver(event: DragOverEvent) {
    const { active, over } = event;
    if (!over) return;
    
    const activeId = active.id as string;
    const overId = over.id as string;

    if (activeId === overId) return;

    // Is it dropping over a container directly?
    const isOverContainer = over.data.current?.sortable?.containerId || overId;
    // ... we handle layout updates in dragEnd to keep it simple, or here for smooth lists.
    // For simplicity, we just handle the final move in dragEnd.
  }

  async function handleDragEnd(event: DragEndEvent) {
    setActiveId(null);
    const { active, over } = event;
    if (!over) return;

    const activeId = active.id as string;
    const overId = over.id as string;

    const activeQuiz = quizzes.find((q) => q.id === activeId);
    if (!activeQuiz) return;

    let targetGroupId: string | null = null;
    let targetIndex = 0;

    // Check if over a group container directly
    const overContainerId = over.data.current?.sortable?.containerId;
    if (overContainerId) {
       targetGroupId = overContainerId === "uncategorized" ? null : overContainerId;
    } else if (groups.find(g => g.id === overId) || overId === "uncategorized") {
       targetGroupId = overId === "uncategorized" ? null : overId;
    } else {
       const overQuiz = quizzes.find((q) => q.id === overId);
       if (overQuiz) {
         targetGroupId = overQuiz.groupId;
       }
    }

    if (targetGroupId !== undefined) {
      setQuizzes((items) => {
        const oldIndex = items.findIndex((q) => q.id === activeId);
        const overIndex = items.findIndex((q) => q.id === overId);
        let newItems = [...items];
        
        newItems[oldIndex].groupId = targetGroupId;

        if (overIndex >= 0 && overIndex !== oldIndex) {
          newItems = arrayMove(newItems, oldIndex, overIndex);
        } else {
          // just moved to end of a group
          const oldItem = newItems.splice(oldIndex, 1)[0];
          newItems.push(oldItem);
        }

        // Re-calculate sortOrder for the affected groups to persist
        const affectedGroups = new Set([activeQuiz.groupId, targetGroupId]);
        const updates: any[] = [];
        
        affectedGroups.forEach(gId => {
           const gItems = newItems.filter(q => q.groupId === gId);
           gItems.forEach((item, index) => {
             item.sortOrder = index;
             updates.push({ id: item.id, sortOrder: index, groupId: item.groupId });
           });
        });

        // Fire API
        fetch("/api/quizzes/reorder", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ items: updates }),
        });

        return newItems;
      });
    }
  }

  // Derive grouped quizzes
  const groupedQuizzes = groups.map(g => ({
    ...g,
    quizzes: quizzes.filter(q => q.groupId === g.id).sort((a,b) => a.sortOrder - b.sortOrder)
  }));
  const uncategorizedQuizzes = quizzes.filter(q => q.groupId === null).sort((a,b) => a.sortOrder - b.sortOrder);

  const activeQuiz = quizzes.find(q => q.id === activeId);

  return (
    <div className="pb-20">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div><p className="text-xs font-bold uppercase tracking-[0.16em] text-primary">Practice</p><h2 className="editorial-title mt-1 text-3xl text-text-heading">Practice quizzes</h2></div>
        <div className="grid grid-cols-2 gap-3 sm:flex">
          <button onClick={() => setIsCreatingGroup(true)} className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl border border-border-light bg-bg-surface px-4 font-bold text-text-heading shadow-sm transition-colors hover:bg-bg-surface-alt">
             Add Group
          </button>
          <button onClick={() => setShowImport(true)} className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-primary px-4 font-bold text-white shadow-sm transition-colors hover:bg-primary-hover">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            Import Quiz
          </button>
        </div>
      </div>

      {isCreatingGroup && (
        <div className="animate-slide-up mb-6 flex flex-col gap-3 rounded-2xl border border-primary/20 bg-bg-surface p-5 shadow-sm sm:flex-row sm:items-center">
          <input
            autoFocus
            type="text"
            value={newGroupName}
            onChange={(e) => setNewGroupName(e.target.value)}
            placeholder="e.g. Exam 1 Quizzes"
            className="flex-1 px-3 py-2 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30"
          />
          <button onClick={handleCreateGroup} className="px-4 py-2 bg-primary text-white font-medium rounded-md hover:bg-primary-hover cursor-pointer">
            Save
          </button>
          <button onClick={() => { setIsCreatingGroup(false); setNewGroupName(""); }} className="px-4 py-2 bg-bg-surface-alt text-text-heading font-medium rounded-md hover:bg-border cursor-pointer">
            Cancel
          </button>
        </div>
      )}

      {/* Editing quiz modal/inline - simplified as a modal-like overlay for simplicity when editing */}
      {editingId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-3xl border border-border bg-bg-surface p-6 shadow-[var(--shadow-modal)]">
            <h3 className="editorial-title mb-4 text-2xl text-text-heading">Edit quiz</h3>
            <input
              type="text"
              value={editName}
              onChange={(e) => setEditName(e.target.value)}
              placeholder="Quiz Name"
              autoFocus
              className="w-full px-3 py-2 mb-3 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
            <textarea
              value={editDescription}
              onChange={(e) => setEditDescription(e.target.value)}
              placeholder="Description (optional)"
              rows={3}
              className="w-full px-3 py-2 mb-4 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none"
            />
            <div className="flex gap-2 justify-end">
              <button onClick={() => setEditingId(null)} className="px-4 py-2 bg-bg-surface-alt text-text-heading font-medium rounded-md hover:bg-border cursor-pointer">Cancel</button>
              <button onClick={() => handleRenameQuiz(editingId)} className="px-4 py-2 bg-primary text-white font-medium rounded-md hover:bg-primary-hover cursor-pointer">Save Changes</button>
            </div>
          </div>
        </div>
      )}

      {!loading && quizzes.length === 0 && groups.length === 0 && (
         <div className="text-center py-16">
            <h3 className="text-lg font-semibold text-text-heading mb-1">No quizzes yet</h3>
            <p className="text-text-secondary mb-4">Import your first quiz or create a group</p>
         </div>
      )}

      {!loading && (
        <DndContext sensors={sensors} collisionDetection={pointerWithin} onDragStart={handleDragStart} onDragOver={handleDragOver} onDragEnd={handleDragEnd}>
          <div className="space-y-8">
            {groupedQuizzes.map(group => (
              <div key={group.id} className="rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5">
                <div className={`flex items-center justify-between ${collapsedGroups[group.id] ? "" : "mb-4"}`}>
                  {editingGroupId === group.id ? (
                     <div className="flex items-center gap-2">
                       <input autoFocus value={editGroupName} onChange={e => setEditGroupName(e.target.value)} className="px-2 py-1 rounded border border-border bg-bg-surface text-text-heading focus:ring-1 focus:ring-primary" />
                       <button onClick={() => handleRenameGroup(group.id)} className="text-xs px-2 py-1 bg-primary text-white rounded">Save</button>
                       <button onClick={() => setEditingGroupId(null)} className="text-xs px-2 py-1 bg-bg-surface text-text-heading rounded border border-border-light">Cancel</button>
                     </div>
                  ) : (
                    <div className="flex items-center gap-2">
                      <button onClick={() => toggleGroup(group.id)} className="p-1 rounded text-text-muted hover:text-text-heading hover:bg-bg-surface transition-colors cursor-pointer" title={collapsedGroups[group.id] ? "Expand" : "Collapse"}>
                        <svg className={`w-5 h-5 transition-transform duration-200 ${collapsedGroups[group.id] ? '-rotate-90' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
                      </button>
                      <h3 className="text-lg font-extrabold text-text-heading">{group.name}</h3>
                    </div>
                  )}
                  
                  <div className="flex items-center gap-2">
                    <ShareMenu targetType="GROUP" contentId={group.id} classSlug={params.classSlug as string} />
                    <button onClick={() => { setEditingGroupId(group.id); setEditGroupName(group.name); }} className="p-1.5 rounded-lg text-text-muted hover:text-text-heading hover:bg-bg-surface transition-colors cursor-pointer"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg></button>
                    <button onClick={() => handleDeleteGroup(group.id, group.name)} className="p-1.5 rounded-lg text-text-muted hover:text-error hover:bg-bg-surface transition-colors cursor-pointer"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg></button>
                  </div>
                </div>
                
                <div className={collapsedGroups[group.id] ? "hidden" : "block"}>
                  <SortableContext id={group.id} items={group.quizzes.map(q => q.id)} strategy={verticalListSortingStrategy}>
                    <DroppableContainer id={group.id}>
                       {group.quizzes.length === 0 ? (
                         <div className="col-span-1 md:col-span-2 text-center py-4 text-text-muted text-sm border-2 border-dashed border-border-light rounded-lg">Drop quizzes here</div>
                       ) : (
                         group.quizzes.map(quiz => (
                           <SortableQuizCard key={quiz.id} quiz={quiz} onEdit={(q: QuizItem) => { setEditingId(q.id); setEditName(q.name); setEditDescription(q.description || ""); }} onDelete={handleDeleteQuiz} classSlug={classSlug} />
                         ))
                       )}
                    </DroppableContainer>
                  </SortableContext>
                </div>
              </div>
            ))}

            {/* Uncategorized */}
            <div className="rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5">
               <div className={`flex items-center gap-2 ${collapsedGroups["uncategorized"] ? "" : "mb-4"}`}>
                 <button onClick={() => toggleGroup("uncategorized")} className="p-1 rounded text-text-muted hover:text-text-heading hover:bg-bg-surface transition-colors cursor-pointer" title={collapsedGroups["uncategorized"] ? "Expand" : "Collapse"}>
                   <svg className={`w-5 h-5 transition-transform duration-200 ${collapsedGroups["uncategorized"] ? '-rotate-90' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
                 </button>
                 <h3 className="text-lg font-semibold text-text-heading">Uncategorized</h3>
               </div>
               
               <div className={collapsedGroups["uncategorized"] ? "hidden" : "block"}>
                 <SortableContext id="uncategorized" items={uncategorizedQuizzes.map(q => q.id)} strategy={verticalListSortingStrategy}>
                    <DroppableContainer id="uncategorized">
                       {uncategorizedQuizzes.length === 0 ? (
                         <div className="col-span-1 md:col-span-2 text-center py-4 text-text-muted text-sm border-2 border-dashed border-border-light rounded-lg">No uncategorized quizzes</div>
                       ) : (
                         uncategorizedQuizzes.map(quiz => (
                           <SortableQuizCard key={quiz.id} quiz={quiz} onEdit={(q: QuizItem) => { setEditingId(q.id); setEditName(q.name); setEditDescription(q.description || ""); }} onDelete={handleDeleteQuiz} classSlug={classSlug} />
                         ))
                       )}
                    </DroppableContainer>
                  </SortableContext>
               </div>
            </div>
          </div>

          <DragOverlay>
            {activeQuiz ? (
              <div className="opacity-80 scale-105 shadow-xl rotate-2">
                 <SortableQuizCard quiz={activeQuiz} onEdit={()=>{}} onDelete={()=>{}} classSlug={classSlug} />
              </div>
            ) : null}
          </DragOverlay>
        </DndContext>
      )}

      {showImport && (
        <ImportModal classId={classId} importType="quizzes" onClose={() => setShowImport(false)} onImported={() => { setShowImport(false); window.location.reload(); }} />
      )}
    </div>
  );
}
