import React, { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, FileUp, FileJson, Check, AlertCircle, Loader2, BrainCircuit, PenTool } from 'lucide-react';
import { useBodyScrollLock } from '../hooks/useBodyScrollLock';
import type { ExportedQuiz, QuizExportFile } from '../types';

interface ImportQuizzesModalProps {
  isOpen: boolean;
  onClose: () => void;
  onImport: (quizzes: ExportedQuiz[]) => Promise<void>;
  parseFile: (file: File) => Promise<QuizExportFile>;
  importing: boolean;
}

type ImportStep = 'upload' | 'select';

export const ImportQuizzesModal: React.FC<ImportQuizzesModalProps> = ({
  isOpen,
  onClose,
  onImport,
  parseFile,
  importing,
}) => {
  const [step, setStep] = useState<ImportStep>('upload');
  const [parsedFile, setParsedFile] = useState<QuizExportFile | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  const [parseError, setParseError] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useBodyScrollLock(isOpen);

  const resetState = () => {
    setStep('upload');
    setParsedFile(null);
    setSelectedIds(new Set());
    setParseError(null);
    setDragActive(false);
  };

  const handleClose = () => {
    resetState();
    onClose();
  };

  const handleFileSelect = async (file: File) => {
    setParseError(null);
    
    if (!file.name.endsWith('.json')) {
      setParseError('Please select a JSON file');
      return;
    }

    try {
      const parsed = await parseFile(file);
      setParsedFile(parsed);
      setSelectedIds(new Set(parsed.quizzes.map((_, i) => i)));
      setStep('select');
    } catch (err) {
      setParseError(err instanceof Error ? err.message : 'Failed to parse file');
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
    
    const file = e.dataTransfer.files[0];
    if (file) handleFileSelect(file);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(true);
  };

  const handleDragLeave = () => {
    setDragActive(false);
  };

  const toggleQuiz = (index: number) => {
    const newSelected = new Set(selectedIds);
    if (newSelected.has(index)) {
      newSelected.delete(index);
    } else {
      newSelected.add(index);
    }
    setSelectedIds(newSelected);
  };

  const toggleAll = () => {
    if (!parsedFile) return;
    if (selectedIds.size === parsedFile.quizzes.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(parsedFile.quizzes.map((_, i) => i)));
    }
  };

  const handleImport = async () => {
    if (!parsedFile || selectedIds.size === 0) return;
    
    const quizzesToImport = parsedFile.quizzes.filter((_, i) => selectedIds.has(i));
    await onImport(quizzesToImport);
    handleClose();
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={handleClose}
          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">Import Quizzes</h2>
                <p className="text-gray-500 font-bold text-sm">
                  {step === 'upload' ? 'Select a Kaboot export file' : `${selectedIds.size} of ${parsedFile?.quizzes.length} selected`}
                </p>
              </div>
              <button
                onClick={handleClose}
                disabled={importing}
                className="p-2 rounded-xl hover:bg-gray-100 transition-colors text-gray-400 hover:text-gray-600 disabled:opacity-50"
              >
                <X size={24} strokeWidth={3} />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-6 bg-gray-50">
              {step === 'upload' && (
                <div className="space-y-4">
                  <div
                    onDrop={handleDrop}
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onClick={() => fileInputRef.current?.click()}
                    className={`border-3 border-dashed rounded-2xl p-12 text-center cursor-pointer transition-all ${
                      dragActive
                        ? 'border-theme-primary bg-theme-primary/5'
                        : 'border-gray-200 hover:border-gray-300 hover:bg-gray-100'
                    }`}
                  >
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept=".json"
                      onChange={(e) => e.target.files?.[0] && handleFileSelect(e.target.files[0])}
                      className="hidden"
                    />
                    <div className="flex flex-col items-center gap-4">
                      <div className={`p-4 rounded-2xl ${dragActive ? 'bg-theme-primary/10' : 'bg-gray-100'}`}>
                        <FileJson size={48} className={dragActive ? 'text-theme-primary' : 'text-gray-400'} />
                      </div>
                      <div>
                        <p className="text-lg font-bold text-gray-700">
                          {dragActive ? 'Drop file here' : 'Drag & drop or click to select'}
                        </p>
                        <p className="text-sm text-gray-400 font-medium mt-1">
                          Accepts .json export files
                        </p>
                      </div>
                    </div>
                  </div>

                  {parseError && (
                    <div className="flex items-center gap-3 bg-red-50 border-2 border-red-100 p-4 rounded-2xl">
                      <AlertCircle size={20} className="text-red-500 flex-shrink-0" />
                      <p className="text-red-600 font-medium">{parseError}</p>
                    </div>
                  )}
                </div>
              )}

              {step === 'select' && parsedFile && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <button
                      onClick={toggleAll}
                      disabled={importing}
                      className="text-sm font-bold text-theme-primary hover:underline disabled:opacity-50"
                    >
                      {selectedIds.size === parsedFile.quizzes.length ? 'Deselect All' : 'Select All'}
                    </button>
                    <p className="text-sm text-gray-400 font-medium">
                      Exported {new Date(parsedFile.exportedAt).toLocaleDateString()}
                    </p>
                  </div>

                  {parsedFile.quizzes.map((quiz, index) => (
                    <motion.div
                      key={index}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.05 }}
                      onClick={() => !importing && toggleQuiz(index)}
                      className={`group bg-white p-4 rounded-2xl border-2 transition-all cursor-pointer ${
                        selectedIds.has(index)
                          ? 'border-theme-primary shadow-md'
                          : 'border-gray-100 hover:border-gray-200'
                      } ${importing ? 'opacity-70 cursor-not-allowed' : ''}`}
                    >
                      <div className="flex items-center gap-4">
                        <div className={`w-6 h-6 rounded-lg border-2 flex items-center justify-center flex-shrink-0 transition-all ${
                          selectedIds.has(index)
                            ? 'bg-theme-primary border-theme-primary'
                            : 'border-gray-300'
                        }`}>
                          {selectedIds.has(index) && (
                            <Check size={16} className="text-white" strokeWidth={3} />
                          )}
                        </div>
                        
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            {quiz.source === 'ai_generated' ? (
                              <span className="bg-purple-100 text-purple-600 px-2 py-0.5 rounded-lg text-xs font-black uppercase tracking-wider flex items-center gap-1">
                                <BrainCircuit size={10} /> AI
                              </span>
                            ) : (
                              <span className="bg-blue-100 text-blue-600 px-2 py-0.5 rounded-lg text-xs font-black uppercase tracking-wider flex items-center gap-1">
                                <PenTool size={10} /> Manual
                              </span>
                            )}
                          </div>
                          <h3 className="text-lg font-bold text-gray-800 truncate">{quiz.title}</h3>
                          <p className="text-sm text-gray-500 font-medium">
                            {quiz.questions.length} question{quiz.questions.length !== 1 ? 's' : ''}
                            {quiz.aiTopic && <span className="text-gray-400"> · {quiz.aiTopic}</span>}
                          </p>
                        </div>
                      </div>
                    </motion.div>
                  ))}
                </div>
              )}
            </div>

            {step === 'select' && (
              <div className="p-6 border-t-2 border-gray-100 bg-white flex gap-3">
                <button
                  onClick={() => setStep('upload')}
                  disabled={importing}
                  className="px-6 py-3 rounded-xl font-bold text-gray-600 bg-gray-100 hover:bg-gray-200 transition-colors disabled:opacity-50"
                >
                  Back
                </button>
                <button
                  onClick={handleImport}
                  disabled={importing || selectedIds.size === 0}
                  className="flex-1 bg-theme-primary text-white px-6 py-3 rounded-xl font-bold shadow-[0_4px_0_var(--theme-primary-dark)] active:shadow-none active:translate-y-[4px] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {importing ? (
                    <>
                      <Loader2 size={20} className="animate-spin" />
                      Importing...
                    </>
                  ) : (
                    <>
                      <FileUp size={20} />
                      Import {selectedIds.size} Quiz{selectedIds.size !== 1 ? 'zes' : ''}
                    </>
                  )}
                </button>
              </div>
            )}
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};
