import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from 'react-oidc-context';
import { motion } from 'framer-motion';
import { BrainCircuit, Play, Loader2, BookmarkPlus, ChevronDown, ChevronUp, AlertCircle, LogIn } from 'lucide-react';
import toast from 'react-hot-toast';
import type { Quiz, Question, GameConfig } from '../types';
import { useAuthenticatedFetch } from '../hooks/useAuthenticatedFetch';

const BACKEND_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001';

interface SharedQuizData {
  title: string;
  source: 'manual' | 'ai_generated';
  aiTopic?: string;
  gameConfig: GameConfig | null;
  questions: Question[];
  questionCount: number;
  sharedBy?: string | null;
}

interface SharedQuizViewProps {
  onHostQuiz: (quiz: Quiz) => void;
  shareToken: string;
}

export const SharedQuizView: React.FC<SharedQuizViewProps> = ({ onHostQuiz, shareToken }) => {
  const token = shareToken;
  const navigate = useNavigate();
  const auth = useAuth();
  const { authFetch } = useAuthenticatedFetch();
  
  const [quizData, setQuizData] = useState<SharedQuizData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [showQuestions, setShowQuestions] = useState(false);

  useEffect(() => {
    const fetchSharedQuiz = async () => {
      if (!token) {
        setError('Invalid share link');
        setLoading(false);
        return;
      }

      try {
        const response = await fetch(`${BACKEND_URL}/api/shared/${token}`);
        
        if (!response.ok) {
          if (response.status === 404) {
            setError('This quiz is no longer available');
          } else {
            setError('Failed to load quiz');
          }
          setLoading(false);
          return;
        }

        const data = await response.json();
        setQuizData(data);
      } catch {
        setError('Failed to load quiz');
      } finally {
        setLoading(false);
      }
    };

    fetchSharedQuiz();
  }, [token]);

  const handleHost = () => {
    if (!quizData) return;
    
    const quiz: Quiz = {
      title: quizData.title,
      questions: quizData.questions,
      config: quizData.gameConfig || undefined,
    };
    
    onHostQuiz(quiz);
  };

  const handleSaveToLibrary = async () => {
    if (!token || !auth.isAuthenticated) return;
    
    setSaving(true);
    try {
      const response = await authFetch(`/api/shared/${token}/copy`, {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('Failed to save quiz');
      }

      const data = await response.json();
      toast.success(`"${data.title}" saved to your library!`);
    } catch {
      toast.error('Failed to save quiz to library');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center h-screen p-4">
        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          className="bg-white text-gray-900 p-8 rounded-[2rem] shadow-[0_10px_0_rgba(0,0,0,0.1)] border-4 border-white/50"
        >
          <Loader2 size={48} className="animate-spin text-theme-primary mx-auto mb-4" />
          <p className="font-bold text-gray-500">Loading shared quiz...</p>
        </motion.div>
      </div>
    );
  }

  if (error || !quizData) {
    return (
      <div className="flex flex-col items-center justify-center h-screen p-4">
        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          className="bg-white text-gray-900 p-8 rounded-[2rem] shadow-[0_10px_0_rgba(0,0,0,0.1)] border-4 border-white/50 text-center max-w-md"
        >
          <div className="bg-red-100 p-4 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4">
            <AlertCircle size={40} className="text-red-500" />
          </div>
          <h2 className="text-2xl font-black text-gray-800 mb-2">Quiz Not Found</h2>
          <p className="text-gray-500 font-medium mb-6">{error || 'This quiz is no longer available'}</p>
          <button
            onClick={() => navigate('/')}
            className="bg-theme-primary text-white px-6 py-3 rounded-2xl font-bold shadow-[0_4px_0_var(--theme-primary-dark)] active:shadow-none active:translate-y-[4px] transition-all"
          >
            Go Home
          </button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-screen p-4">
      <motion.div
        initial={{ scale: 0.8, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        transition={{ type: "spring", bounce: 0.4 }}
        className="bg-white text-gray-900 p-6 md:p-8 rounded-[2rem] shadow-[0_10px_0_rgba(0,0,0,0.1)] border-4 border-white/50 max-w-lg w-full"
      >
        <div className="flex justify-center mb-4">
          <div className="bg-theme-primary p-3 rounded-2xl rotate-3 shadow-lg">
            <BrainCircuit size={32} className="text-white" />
          </div>
        </div>

        <div className="text-center mb-6">
          <p className="text-gray-400 font-bold text-sm uppercase tracking-wider mb-1">
            {quizData.sharedBy ? `Shared by ${quizData.sharedBy}` : 'Shared Quiz'}
          </p>
          <h1 className="text-3xl md:text-4xl font-black text-gray-800 mb-2">{quizData.title}</h1>
          <p className="text-gray-500 font-medium">
            {quizData.questionCount} question{quizData.questionCount !== 1 ? 's' : ''}
            {quizData.aiTopic && <span className="text-gray-400"> • {quizData.aiTopic}</span>}
          </p>
        </div>

        <div className="space-y-3 mb-6">
          <button
            onClick={handleHost}
            className="w-full bg-[#333] text-white py-4 rounded-2xl text-xl font-black shadow-[0_6px_0_#000] active:shadow-none active:translate-y-[6px] transition-all hover:bg-black flex items-center justify-center gap-3"
          >
            <Play size={24} fill="currentColor" /> Host Game
          </button>

          {auth.isAuthenticated ? (
            <button
              onClick={handleSaveToLibrary}
              disabled={saving}
              className="w-full bg-white border-2 border-theme-primary text-theme-primary py-3 rounded-2xl text-lg font-black hover:bg-theme-hover shadow-[0_4px_0_var(--theme-primary)] active:shadow-none active:translate-y-[4px] transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? (
                <>
                  <Loader2 size={20} className="animate-spin" /> Saving...
                </>
              ) : (
                <>
                  <BookmarkPlus size={20} /> Save to My Library
                </>
              )}
            </button>
          ) : (
            <button
              onClick={() => {
                sessionStorage.setItem('kaboot_auth_return_url', window.location.pathname);
                auth.signinRedirect();
              }}
              className="w-full bg-gray-100 text-gray-600 py-3 rounded-2xl text-lg font-black hover:bg-gray-200 shadow-[0_4px_0_#d1d5db] active:shadow-none active:translate-y-[4px] transition-all flex items-center justify-center gap-2"
            >
              <LogIn size={20} /> Sign in to Save
            </button>
          )}
        </div>

        <button
          onClick={() => setShowQuestions(!showQuestions)}
          className="w-full flex items-center justify-center gap-2 text-gray-400 font-bold hover:text-gray-600 transition-colors py-2"
        >
          {showQuestions ? (
            <>
              <ChevronUp size={20} /> Hide Questions
            </>
          ) : (
            <>
              <ChevronDown size={20} /> Preview Questions
            </>
          )}
        </button>

        {showQuestions && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            className="mt-4 space-y-3 max-h-64 overflow-y-auto"
          >
            {quizData.questions.map((q, i) => (
              <div key={q.id} className="bg-gray-50 p-3 rounded-xl">
                <p className="text-sm font-bold text-gray-400 mb-1">Question {i + 1}</p>
                <p className="font-bold text-gray-700">{q.text}</p>
              </div>
            ))}
          </motion.div>
        )}

        <div className="mt-6 pt-4 border-t border-gray-100 text-center">
          <button
            onClick={() => navigate('/')}
            className="text-gray-400 font-bold hover:text-gray-600 transition-colors"
          >
            ← Back to Home
          </button>
        </div>
      </motion.div>
    </div>
  );
};
