import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Trash2, Play, BrainCircuit, PenTool, Loader2, Calendar } from 'lucide-react';
import { QuizListItem } from '../types';
import { useBodyScrollLock } from '../hooks/useBodyScrollLock';

interface QuizLibraryProps {
  isOpen: boolean;
  onClose: () => void;
  quizzes: QuizListItem[];
  loading: boolean;
  loadingQuizId: string | null;
  deletingQuizId: string | null;
  error: string | null;
  onLoadQuiz: (id: string) => void;
  onDeleteQuiz: (id: string) => void;
  onRetry: () => void;
}

export const QuizLibrary: React.FC<QuizLibraryProps> = ({
  isOpen,
  onClose,
  quizzes,
  loading,
  loadingQuizId,
  deletingQuizId,
  error,
  onLoadQuiz,
  onDeleteQuiz,
  onRetry,
}) => {
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const isAnyOperationInProgress = loading || !!loadingQuizId || !!deletingQuizId;

  useBodyScrollLock(isOpen);

  const handleDeleteClick = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    setConfirmDeleteId(id);
  };

  const confirmDelete = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (confirmDeleteId) {
      try {
        await onDeleteQuiz(confirmDeleteId);
        setConfirmDeleteId(null);
      } catch {
        setConfirmDeleteId(null);
      }
    }
  };

  const cancelDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    setConfirmDeleteId(null);
  };

  const formatDate = (dateString: string) => {
    try {
      return new Date(dateString).toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      });
    } catch (e) {
      return dateString;
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.9, opacity: 0, y: 20 }}
              transition={{ type: "spring", bounce: 0.4 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-white w-full max-w-2xl max-h-[80vh] flex flex-col rounded-[2rem] shadow-[0_10px_0_rgba(0,0,0,0.1)] border-4 border-white/50 relative overflow-hidden"
            >
              <div className="p-6 border-b-2 border-gray-100 flex justify-between items-center bg-white sticky top-0 z-10">
                <div>
                  <h2 className="text-3xl font-black text-gray-900 tracking-tight">My Library</h2>
                  <p className="text-gray-500 font-bold text-sm">Select a quiz to play</p>
                </div>
                <button
                  onClick={onClose}
                  className="p-2 rounded-xl hover:bg-gray-100 transition-colors text-gray-400 hover:text-gray-600"
                >
                  <X size={24} strokeWidth={3} />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-6 space-y-4 bg-gray-50">
                {loading && (
                  <div className="flex flex-col items-center justify-center py-12 text-gray-400">
                    <Loader2 size={48} className="animate-spin mb-4 text-theme-primary" />
                    <p className="font-bold">Loading your quizzes...</p>
                  </div>
                )}

                {!loading && error && (
                  <div className="bg-red-50 border-2 border-red-100 p-4 rounded-2xl text-center">
                    <p className="text-red-500 font-bold mb-3">{error}</p>
                    <button
                      onClick={onRetry}
                      className="bg-red-500 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-red-600 transition-colors"
                    >
                      Try Again
                    </button>
                  </div>
                )}

                {!loading && !error && quizzes.length === 0 && (
                  <div className="text-center py-12 space-y-4">
                    <div className="bg-gray-100 w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4">
                      <BrainCircuit size={40} className="text-gray-300" />
                    </div>
                    <h3 className="text-xl font-black text-gray-400">No saved quizzes yet</h3>
                    <p className="text-gray-400 font-medium">Create or generate a quiz to save it here!</p>
                  </div>
                )}

                {!loading && !error && quizzes.map((quiz) => (
                  <motion.div
                    key={quiz.id}
                    layout
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className={`group bg-white p-4 rounded-2xl border-2 border-gray-100 hover:border-theme-primary hover:shadow-md transition-all relative overflow-hidden ${isAnyOperationInProgress ? 'cursor-not-allowed opacity-70' : 'cursor-pointer'}`}
                    onClick={() => !isAnyOperationInProgress && onLoadQuiz(quiz.id)}
                  >
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          {quiz.source === 'ai_generated' ? (
                            <span className="bg-purple-100 text-purple-600 px-2 py-1 rounded-lg text-xs font-black uppercase tracking-wider flex items-center gap-1">
                              <BrainCircuit size={12} /> AI
                            </span>
                          ) : (
                            <span className="bg-blue-100 text-blue-600 px-2 py-1 rounded-lg text-xs font-black uppercase tracking-wider flex items-center gap-1">
                              <PenTool size={12} /> Manual
                            </span>
                          )}
                          <span className="text-gray-400 text-xs font-bold flex items-center gap-1">
                            <Calendar size={12} /> {formatDate(quiz.createdAt)}
                          </span>
                        </div>
                        
                        <h3 className="text-xl font-black text-gray-800 mb-1 group-hover:text-theme-primary transition-colors">
                          {quiz.title}
                        </h3>
                        
                        <p className="text-gray-500 font-medium text-sm">
                          {quiz.questionCount} question{quiz.questionCount !== 1 ? 's' : ''} 
                          {quiz.aiTopic && <span className="text-gray-400"> • Topic: {quiz.aiTopic}</span>}
                        </p>
                      </div>

                      <div className="flex items-center gap-3 pl-4">
                        {loadingQuizId === quiz.id ? (
                          <div className="p-3">
                            <Loader2 size={24} className="animate-spin text-theme-primary" />
                          </div>
                        ) : deletingQuizId === quiz.id ? (
                          <div className="p-3">
                            <Loader2 size={24} className="animate-spin text-red-500" />
                          </div>
                        ) : confirmDeleteId === quiz.id ? (
                          <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
                            <button
                              onClick={confirmDelete}
                              disabled={isAnyOperationInProgress}
                              className="bg-red-500 text-white px-3 py-2 rounded-xl text-sm font-bold shadow-[0_3px_0_#991b1b] active:shadow-none active:translate-y-[3px] transition-all disabled:opacity-50"
                            >
                              Confirm
                            </button>
                            <button
                              onClick={cancelDelete}
                              disabled={isAnyOperationInProgress}
                              className="bg-gray-200 text-gray-600 px-3 py-2 rounded-xl text-sm font-bold hover:bg-gray-300 transition-all disabled:opacity-50"
                            >
                              Cancel
                            </button>
                          </div>
                        ) : (
                          <>
                            <button
                              onClick={(e) => handleDeleteClick(e, quiz.id)}
                              disabled={isAnyOperationInProgress}
                              className="p-3 rounded-xl text-gray-300 hover:bg-red-50 hover:text-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Delete quiz"
                            >
                              <Trash2 size={20} />
                            </button>
                            <div className="bg-theme-primary/10 p-3 rounded-xl text-theme-primary group-hover:bg-theme-primary group-hover:text-white transition-all">
                              <Play size={24} fill="currentColor" />
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};
