import React, { useState, useEffect } from 'react';
import { BookOpen, Users, Lock, Key, LogOut, ExternalLink, ChevronRight, GraduationCap, Beaker, Globe, Calculator, BookText, Languages } from 'lucide-react';

const UnifiedPlatform = () => {
  const [currentPage, setCurrentPage] = useState('home');
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [userType, setUserType] = useState(null);
  const [schoolCode, setSchoolCode] = useState('');
  const [adminPassword, setAdminPassword] = useState('');
  const [loginError, setLoginError] = useState('');
  const [schoolCodes, setSchoolCodes] = useState([]);
  const [newCodeName, setNewCodeName] = useState('');
  const [generatedCode, setGeneratedCode] = useState('');

  const ADMIN_PASSWORD = '@mikaelJ46';

  // Platform links
  const platforms = [
    {
      id: 'chemistry-biology',
      name: 'Chemistry & Biology',
      description: 'Deep understanding focus with AI-powered learning',
      icon: <Beaker className="w-8 h-8" />,
      url: 'https://huggingface.co/spaces/YOUR_USERNAME/chemistry-biology',
      color: 'bg-green-500',
      subjects: ['Chemistry', 'Biology']
    },
    {
      id: 'geography-history-business',
      name: 'Geography, History & Business',
      description: 'Comprehensive humanities and business studies',
      icon: <Globe className="w-8 h-8" />,
      url: 'https://huggingface.co/spaces/YOUR_USERNAME/geography-history-business',
      color: 'bg-blue-500',
      subjects: ['Geography', 'History', 'Business']
    },
    {
      id: 'languages',
      name: 'French & EFL',
      description: 'Language learning with AI translation and dictionary',
      icon: <Languages className="w-8 h-8" />,
      url: 'https://huggingface.co/spaces/YOUR_USERNAME/languages',
      color: 'bg-purple-500',
      subjects: ['French', 'EFL']
    },
    {
      id: 'math-physics',
      name: 'Mathematics & Physics',
      description: 'Step-by-step problem solving and practice',
      icon: <Calculator className="w-8 h-8" />,
      url: 'https://huggingface.co/spaces/YOUR_USERNAME/math-physics',
      color: 'bg-orange-500',
      subjects: ['Mathematics', 'Physics']
    }
  ];

  // Load school codes from storage
  useEffect(() => {
    const loadCodes = async () => {
      try {
        const result = await window.storage.list('school_code:');
        if (result && result.keys) {
          const codes = [];
          for (const key of result.keys) {
            const data = await window.storage.get(key);
            if (data) {
              codes.push(JSON.parse(data.value));
            }
          }
          setSchoolCodes(codes);
        }
      } catch (error) {
        console.log('No codes yet or error loading:', error);
      }
    };
    loadCodes();
  }, []);

  // Generate random school code
  const generateCode = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
  };

  // Admin: Create new school code
  const handleCreateCode = async () => {
    if (!newCodeName.trim()) {
      alert('Please enter a school/code name');
      return;
    }

    const code = generateCode();
    const codeData = {
      code: code,
      name: newCodeName,
      createdAt: new Date().toISOString(),
      active: true
    };

    try {
      await window.storage.set(`school_code:${code}`, JSON.stringify(codeData));
      setSchoolCodes([...schoolCodes, codeData]);
      setGeneratedCode(code);
      setNewCodeName('');
    } catch (error) {
      alert('Error creating code: ' + error.message);
    }
  };

  // Admin: Toggle code active status
  const toggleCodeStatus = async (code) => {
    try {
      const result = await window.storage.get(`school_code:${code}`);
      if (result) {
        const codeData = JSON.parse(result.value);
        codeData.active = !codeData.active;
        await window.storage.set(`school_code:${code}`, JSON.stringify(codeData));
        setSchoolCodes(schoolCodes.map(c => c.code === code ? codeData : c));
      }
    } catch (error) {
      alert('Error updating code: ' + error.message);
    }
  };

  // Handle admin login
  const handleAdminLogin = () => {
    if (adminPassword === ADMIN_PASSWORD) {
      setIsAuthenticated(true);
      setUserType('admin');
      setCurrentPage('admin-dashboard');
      setLoginError('');
    } else {
      setLoginError('Incorrect admin password');
    }
  };

  // Handle student login
  const handleStudentLogin = async () => {
    if (!schoolCode.trim()) {
      setLoginError('Please enter a school code');
      return;
    }

    try {
      const result = await window.storage.get(`school_code:${schoolCode.toUpperCase()}`);
      if (result) {
        const codeData = JSON.parse(result.value);
        if (codeData.active) {
          setIsAuthenticated(true);
          setUserType('student');
          setCurrentPage('student-dashboard');
          setLoginError('');
        } else {
          setLoginError('This school code has been deactivated');
        }
      } else {
        setLoginError('Invalid school code');
      }
    } catch (error) {
      setLoginError('Invalid school code');
    }
  };

  // Handle logout
  const handleLogout = () => {
    setIsAuthenticated(false);
    setUserType(null);
    setCurrentPage('home');
    setSchoolCode('');
    setAdminPassword('');
    setLoginError('');
  };

  // Open platform in same tab
  const openPlatform = (url) => {
    window.location.href = url;
  };

  // HOME PAGE
  if (currentPage === 'home') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
        {/* Header */}
        <header className="bg-white shadow-sm border-b">
          <div className="max-w-7xl mx-auto px-4 py-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <GraduationCap className="w-10 h-10 text-blue-600" />
                <div>
                  <h1 className="text-3xl font-bold text-gray-900">IGCSE/GCSE Master</h1>
                  <p className="text-sm text-gray-600">AI-Powered Learning Platform</p>
                </div>
              </div>
              <button
                onClick={() => setCurrentPage('login-choice')}
                className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold"
              >
                <Lock className="w-5 h-5" />
                Login
              </button>
            </div>
          </div>
        </header>

        {/* Hero Section */}
        <section className="max-w-7xl mx-auto px-4 py-16 text-center">
          <h2 className="text-5xl font-bold text-gray-900 mb-6">
            Master Your IGCSE & GCSE Exams with AI
          </h2>
          <p className="text-xl text-gray-600 mb-8 max-w-3xl mx-auto">
            Comprehensive learning platform covering all major subjects with AI tutors, practice questions, past papers, and deep understanding focus.
          </p>
          <div className="flex items-center justify-center gap-4 flex-wrap">
            <div className="flex items-center gap-2 px-4 py-2 bg-green-100 text-green-800 rounded-full font-semibold">
              <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
              Multi-AI System Active
            </div>
            <div className="px-4 py-2 bg-blue-100 text-blue-800 rounded-full font-semibold">
              8 Subjects Covered
            </div>
            <div className="px-4 py-2 bg-purple-100 text-purple-800 rounded-full font-semibold">
              IGCSE & GCSE
            </div>
          </div>
        </section>

        {/* Platforms Grid */}
        <section className="max-w-7xl mx-auto px-4 py-12">
          <h3 className="text-3xl font-bold text-gray-900 mb-8 text-center">Our Learning Platforms</h3>
          <div className="grid md:grid-cols-2 gap-6">
            {platforms.map((platform) => (
              <div
                key={platform.id}
                className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all p-6 border-2 border-gray-100 hover:border-blue-300"
              >
                <div className="flex items-start gap-4">
                  <div className={`${platform.color} p-4 rounded-lg text-white`}>
                    {platform.icon}
                  </div>
                  <div className="flex-1">
                    <h4 className="text-xl font-bold text-gray-900 mb-2">{platform.name}</h4>
                    <p className="text-gray-600 mb-4">{platform.description}</p>
                    <div className="flex flex-wrap gap-2">
                      {platform.subjects.map((subject) => (
                        <span key={subject} className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm font-medium">
                          {subject}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* Features */}
        <section className="max-w-7xl mx-auto px-4 py-16">
          <h3 className="text-3xl font-bold text-gray-900 mb-12 text-center">Platform Features</h3>
          <div className="grid md:grid-cols-3 gap-8">
            <div className="text-center">
              <div className="bg-blue-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <BookOpen className="w-8 h-8 text-blue-600" />
              </div>
              <h4 className="text-xl font-bold mb-2">AI Tutors</h4>
              <p className="text-gray-600">Get personalized help from AI tutors with deep understanding focus</p>
            </div>
            <div className="text-center">
              <div className="bg-green-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <BookText className="w-8 h-8 text-green-600" />
              </div>
              <h4 className="text-xl font-bold mb-2">Past Papers</h4>
              <p className="text-gray-600">Access and practice with real exam questions indexed by topic</p>
            </div>
            <div className="text-center">
              <div className="bg-purple-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <Key className="w-8 h-8 text-purple-600" />
              </div>
              <h4 className="text-xl font-bold mb-2">Practice Questions</h4>
              <p className="text-gray-600">Generate unlimited practice questions with detailed feedback</p>
            </div>
          </div>
        </section>

        {/* Footer */}
        <footer className="bg-gray-900 text-white py-8 mt-16">
          <div className="max-w-7xl mx-auto px-4 text-center">
            <p className="text-gray-400">© 2024 IGCSE/GCSE Master. Powered by Gemini AI, Cohere, Z.ai & MiniMax</p>
            <p className="text-sm text-gray-500 mt-2">Multi-AI fallback system ensures 24/7 availability</p>
          </div>
        </footer>
      </div>
    );
  }

  // LOGIN CHOICE PAGE
  if (currentPage === 'login-choice') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 flex items-center justify-center p-4">
        <div className="max-w-2xl w-full">
          <button
            onClick={() => setCurrentPage('home')}
            className="mb-6 text-blue-600 hover:text-blue-700 flex items-center gap-2"
          >
            ← Back to Home
          </button>
          
          <div className="bg-white rounded-xl shadow-2xl p-8 mb-6 text-center">
            <GraduationCap className="w-16 h-16 text-blue-600 mx-auto mb-4" />
            <h2 className="text-3xl font-bold text-gray-900 mb-2">Welcome Back!</h2>
            <p className="text-gray-600">Choose how you'd like to login</p>
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            <button
              onClick={() => setCurrentPage('student-login')}
              className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all p-8 text-center group"
            >
              <Users className="w-16 h-16 text-blue-600 mx-auto mb-4 group-hover:scale-110 transition-transform" />
              <h3 className="text-2xl font-bold text-gray-900 mb-2">Student Login</h3>
              <p className="text-gray-600 mb-4">Login with your school code</p>
              <ChevronRight className="w-6 h-6 text-blue-600 mx-auto" />
            </button>

            <button
              onClick={() => setCurrentPage('admin-login')}
              className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all p-8 text-center group"
            >
              <Lock className="w-16 h-16 text-purple-600 mx-auto mb-4 group-hover:scale-110 transition-transform" />
              <h3 className="text-2xl font-bold text-gray-900 mb-2">Admin Login</h3>
              <p className="text-gray-600 mb-4">Manage school codes</p>
              <ChevronRight className="w-6 h-6 text-purple-600 mx-auto" />
            </button>
          </div>
        </div>
      </div>
    );
  }

  // STUDENT LOGIN PAGE
  if (currentPage === 'student-login') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 flex items-center justify-center p-4">
        <div className="max-w-md w-full">
          <button
            onClick={() => setCurrentPage('login-choice')}
            className="mb-6 text-blue-600 hover:text-blue-700 flex items-center gap-2"
          >
            ← Back
          </button>

          <div className="bg-white rounded-xl shadow-2xl p-8">
            <div className="text-center mb-8">
              <Users className="w-16 h-16 text-blue-600 mx-auto mb-4" />
              <h2 className="text-3xl font-bold text-gray-900 mb-2">Student Login</h2>
              <p className="text-gray-600">Enter your school code to access all platforms</p>
            </div>

            {loginError && (
              <div className="mb-4 p-3 bg-red-100 border border-red-300 text-red-700 rounded-lg text-sm">
                {loginError}
              </div>
            )}

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">School Code</label>
                <input
                  type="text"
                  value={schoolCode}
                  onChange={(e) => setSchoolCode(e.target.value.toUpperCase())}
                  onKeyPress={(e) => e.key === 'Enter' && handleStudentLogin()}
                  placeholder="Enter 8-character code"
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-center text-xl font-mono tracking-wider"
                  maxLength={8}
                />
              </div>

              <button
                onClick={handleStudentLogin}
                className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold text-lg"
              >
                Login to Dashboard
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ADMIN LOGIN PAGE
  if (currentPage === 'admin-login') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 flex items-center justify-center p-4">
        <div className="max-w-md w-full">
          <button
            onClick={() => setCurrentPage('login-choice')}
            className="mb-6 text-purple-600 hover:text-purple-700 flex items-center gap-2"
          >
            ← Back
          </button>

          <div className="bg-white rounded-xl shadow-2xl p-8">
            <div className="text-center mb-8">
              <Lock className="w-16 h-16 text-purple-600 mx-auto mb-4" />
              <h2 className="text-3xl font-bold text-gray-900 mb-2">Admin Login</h2>
              <p className="text-gray-600">Enter admin password to manage school codes</p>
            </div>

            {loginError && (
              <div className="mb-4 p-3 bg-red-100 border border-red-300 text-red-700 rounded-lg text-sm">
                {loginError}
              </div>
            )}

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Admin Password</label>
                <input
                  type="password"
                  value={adminPassword}
                  onChange={(e) => setAdminPassword(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleAdminLogin()}
                  placeholder="Enter password"
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                />
              </div>

              <button
                onClick={handleAdminLogin}
                className="w-full py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-semibold text-lg"
              >
                Login to Admin Panel
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // STUDENT DASHBOARD
  if (currentPage === 'student-dashboard' && isAuthenticated && userType === 'student') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
        <header className="bg-white shadow-sm border-b">
          <div className="max-w-7xl mx-auto px-4 py-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <GraduationCap className="w-10 h-10 text-blue-600" />
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">Student Dashboard</h1>
                  <p className="text-sm text-gray-600">Code: {schoolCode}</p>
                </div>
              </div>
              <button
                onClick={handleLogout}
                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
              >
                <LogOut className="w-4 h-4" />
                Logout
              </button>
            </div>
          </div>
        </header>

        <div className="max-w-7xl mx-auto px-4 py-8">
          <h2 className="text-3xl font-bold text-gray-900 mb-8">Choose Your Subject Platform</h2>
          
          <div className="grid md:grid-cols-2 gap-6">
            {platforms.map((platform) => (
              <div
                key={platform.id}
                className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all p-6 border-2 border-gray-100 hover:border-blue-300"
              >
                <div className="flex items-start gap-4 mb-4">
                  <div className={`${platform.color} p-4 rounded-lg text-white`}>
                    {platform.icon}
                  </div>
                  <div className="flex-1">
                    <h3 className="text-xl font-bold text-gray-900 mb-2">{platform.name}</h3>
                    <p className="text-gray-600 mb-3">{platform.description}</p>
                    <div className="flex flex-wrap gap-2 mb-4">
                      {platform.subjects.map((subject) => (
                        <span key={subject} className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm font-medium">
                          {subject}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
                
                <button
                  onClick={() => openPlatform(platform.url)}
                  className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold flex items-center justify-center gap-2"
                >
                  Open Platform
                  <ChevronRight className="w-5 h-5" />
                </button>
              </div>
            ))}
          </div>

          <div className="mt-12 bg-blue-50 rounded-xl p-6 border-2 border-blue-200">
            <h3 className="text-xl font-bold text-gray-900 mb-4">📚 Platform Features Available:</h3>
            <ul className="grid md:grid-cols-2 gap-3">
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>AI Tutors with deep understanding focus</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>Past papers indexed by topic</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>Unlimited practice questions</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>Detailed feedback and marking</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>Multi-AI fallback system</span>
              </li>
              <li className="flex items-center gap-2">
                <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                <span>24/7 availability</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    );
  }

  // ADMIN DASHBOARD
  if (currentPage === 'admin-dashboard' && isAuthenticated && userType === 'admin') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50">
        <header className="bg-white shadow-sm border-b">
          <div className="max-w-7xl mx-auto px-4 py-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Lock className="w-10 h-10 text-purple-600" />
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">Admin Panel</h1>
                  <p className="text-sm text-gray-600">Manage school access codes</p>
                </div>
              </div>
              <button
                onClick={handleLogout}
                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
              >
                <LogOut className="w-4 h-4" />
                Logout
              </button>
            </div>
          </div>
        </header>

        <div className="max-w-7xl mx-auto px-4 py-8">
          {/* Create New Code */}
          <div className="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">Generate New School Code</h2>
            
            <div className="flex gap-4 mb-4">
              <input
                type="text"
                value={newCodeName}
                onChange={(e) => setNewCodeName(e.target.value)}
                placeholder="Enter school or code name"
                className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              />
              <button
                onClick={handleCreateCode}
                className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-semibold flex items-center gap-2"
              >
                <Key className="w-5 h-5" />
                Generate Code
              </button>
            </div>

            {generatedCode && (
              <div className="p-4 bg-green-50 border-2 border-green-300 rounded-lg">
                <p className="text-sm text-green-800 mb-2 font-semibold">✅ New code generated successfully!</p>
                <div className="flex items-center gap-2">
                  <code className="flex-1 px-4 py-3 bg-white border-2 border-green-400 rounded-lg text-2xl font-mono font-bold text-center">
                    {generatedCode}
                  </code>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(generatedCode);
                      alert('Code copied to clipboard!');
                    }}
                    className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
                  >
                    Copy
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Active Codes List */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">
              All School Codes ({schoolCodes.length})
            </h2>

            {schoolCodes.length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                <Key className="w-16 h-16 mx-auto mb-4 opacity-50" />
                <p>No school codes generated yet</p>
              </div>
            ) : (
              <div className="space-y-3">
                {schoolCodes.map((codeData) => (
                  <div
                    key={codeData.code}
                    className={`p-4 border-2 rounded-lg flex items-center justify-between ${
                      codeData.active ? 'bg-green-50 border-green-300' : 'bg-gray-50 border-gray-300'
                    }`}
                  >
                    <div className="flex items-center gap-4">
                      <code className="px-4 py-2 bg-white border rounded font-mono font-bold text-lg">
                        {codeData.code}
                      </code>
                      <div>
                        <p className="font-semibold text-gray-900">{codeData.name}</p>
                        <p className="text-sm text-gray-600">
                          Created: {new Date(codeData.createdAt).toLocaleString()}
                        </p>
                      </div>
                    </div>
                    
                    <button
                      onClick={() => toggleCodeStatus(codeData.code)}
                      className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
                        codeData.active
                          ? 'bg-red-100 text-red-700 hover:bg-red-200'
                          : 'bg-green-100 text-green-700 hover:bg-green-200'
                      }`}
                    >
                      {codeData.active ? 'Deactivate' : 'Activate'}