import React, { useState } from 'react';
import { BookOpen, CheckCircle, XCircle, ArrowRight, Trophy, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Progress } from '@/components/ui/progress';

interface Module {
  id: string;
  title: string;
  description: string;
  content: string;
  whyItMatters: string;
  examples: string[];
  tips: string[];
  quiz: QuizQuestion[];
}

interface QuizQuestion {
  question: string;
  options: string[];
  correctIndex: number;
}

const modules: Module[] = [
  {
    id: 'fundamentals',
    title: 'Cybersecurity Fundamentals',
    description: 'Learn the core concepts of cybersecurity',
    content: 'Cybersecurity is the practice of protecting systems, networks, and programs from digital attacks. These attacks are usually aimed at accessing, changing, or destroying sensitive information, extorting money from users, or interrupting normal business processes.',
    whyItMatters: 'In our increasingly connected world, cyberattacks are becoming more sophisticated. Understanding the basics helps you protect your personal and professional digital life.',
    examples: ['Data breaches at major companies', 'Ransomware attacks on hospitals', 'Identity theft through social engineering', 'State-sponsored cyber espionage'],
    tips: ['Keep all software updated', 'Use strong, unique passwords', 'Enable two-factor authentication', 'Be skeptical of unexpected emails', 'Regularly back up your data'],
    quiz: [
      { question: 'What is the primary goal of cybersecurity?', options: ['Making websites faster', 'Protecting digital systems from attacks', 'Creating new software', 'Selling antivirus software'], correctIndex: 1 },
      { question: 'Which is NOT a common type of cyberattack?', options: ['Phishing', 'Ransomware', 'Firewall', 'Malware'], correctIndex: 2 },
      { question: 'True or False: Only large companies need cybersecurity.', options: ['True', 'False'], correctIndex: 1 },
      { question: 'What does 2FA stand for?', options: ['Two-Factor Authentication', 'Two-File Access', 'Total Firewall Access', 'Triple Firewall Authentication'], correctIndex: 0 },
      { question: 'Which is a best practice for password security?', options: ['Using the same password everywhere', 'Writing passwords on sticky notes', 'Using unique passwords for each account', 'Sharing passwords with friends'], correctIndex: 2 },
    ],
  },
  {
    id: 'password-security',
    title: 'Password Security',
    description: 'Master the art of creating and managing passwords',
    content: 'Passwords are your first line of defense against unauthorized access. A strong password is long, complex, and unique for each account. Password managers help you create and store these securely.',
    whyItMatters: 'Weak passwords are involved in over 80% of data breaches. A compromised password can lead to identity theft, financial loss, and privacy violations.',
    examples: ['Dictionary attacks cracking simple passwords', 'Credential stuffing from leaked databases', 'Brute force attacks on short passwords', 'Social engineering to guess security questions'],
    tips: ['Use at least 12 characters', 'Mix uppercase, lowercase, numbers, and symbols', 'Never reuse passwords', 'Use a password manager', 'Enable biometric authentication when available'],
    quiz: [
      { question: 'What is the minimum recommended password length?', options: ['4 characters', '8 characters', '12 characters', '6 characters'], correctIndex: 2 },
      { question: 'Which password is strongest?', options: ['password123', 'MyDog2020', 'Tr0ub4dor&3', 'qwerty'], correctIndex: 2 },
      { question: 'What is a password manager?', options: ['A person who remembers passwords', 'Software that stores passwords securely', 'A type of virus', 'A password generator only'], correctIndex: 1 },
      { question: 'True or False: You should change passwords every month.', options: ['True', 'False - only when compromised'], correctIndex: 1 },
      { question: 'What is credential stuffing?', options: ['Creating fake credentials', 'Using leaked passwords to try other accounts', 'Stuffing papers in a safe', 'A type of encryption'], correctIndex: 1 },
    ],
  },
  {
    id: 'phishing',
    title: 'Phishing Detection',
    description: 'Identify and avoid phishing attacks',
    content: 'Phishing is a cyberattack that uses disguised emails, messages, or websites to trick people into revealing sensitive information. Attackers often impersonate trusted entities like banks, tech companies, or colleagues.',
    whyItMatters: 'Phishing is the most common entry point for cyberattacks. One click on a malicious link can compromise your entire digital identity or infect your organization.',
    examples: ['Fake bank emails asking to verify account', 'CEO fraud requesting wire transfers', 'Package delivery notifications with malicious links', 'Tech support scams claiming virus infection'],
    tips: ['Check sender email addresses carefully', 'Hover over links before clicking', 'Look for spelling and grammar errors', 'Never provide credentials via email', 'When in doubt, contact the company directly'],
    quiz: [
      { question: 'What is the main goal of phishing?', options: ['Catching fish', 'Stealing sensitive information', 'Sending spam', 'Testing email systems'], correctIndex: 1 },
      { question: 'Which is a red flag in a phishing email?', options: ['Company logo', 'Urgent language requiring immediate action', 'Professional greeting', 'Contact information'], correctIndex: 1 },
      { question: 'What should you do if you receive a suspicious email?', options: ['Click all links to investigate', 'Reply with your password', 'Delete it and report if possible', 'Forward to everyone'], correctIndex: 2 },
      { question: 'What is spear phishing?', options: ['Random mass emails', 'Targeted attacks on specific individuals', 'Fishing with a spear', 'A type of malware'], correctIndex: 1 },
      { question: 'True or False: Phishing only happens via email.', options: ['True', 'False - also SMS, calls, social media'], correctIndex: 1 },
    ],
  },
  {
    id: 'safe-browsing',
    title: 'Safe Browsing',
    description: 'Navigate the web securely',
    content: 'Safe browsing involves practices that protect you from malicious websites, tracking, and online threats. This includes using secure connections, avoiding suspicious sites, and managing your digital footprint.',
    whyItMatters: 'The internet is full of threats from malicious ads to fake websites. Safe browsing protects your privacy, finances, and devices from compromise.',
    examples: ['Drive-by downloads from compromised sites', 'Fake shopping websites stealing payment info', 'Malicious browser extensions', 'Tracking cookies profiling your behavior'],
    tips: ['Always check for HTTPS', 'Use ad blockers', 'Keep browsers updated', 'Clear cookies regularly', 'Use private browsing for sensitive activities'],
    quiz: [
      { question: 'What does HTTPS indicate?', options: ['Faster website', 'Encrypted connection', 'Government website', 'Popular website'], correctIndex: 1 },
      { question: 'Which browser feature helps privacy?', options: ['Saving passwords', 'Private/Incognito mode', 'Autofill', 'Extensions'], correctIndex: 1 },
      { question: 'What are cookies in web browsing?', options: ['Snacks', 'Small data files websites store', 'Viruses', 'Advertisements'], correctIndex: 1 },
      { question: 'True or False: Public WiFi is always safe to use.', options: ['True', 'False'], correctIndex: 1 },
      { question: 'What should you check before entering payment info?', options: ['Website colors', 'HTTPS and padlock icon', 'Number of visitors', 'Website age'], correctIndex: 1 },
    ],
  },
  {
    id: 'malware',
    title: 'Malware & Viruses',
    description: 'Understand and defend against malicious software',
    content: 'Malware is software designed to harm, exploit, or otherwise compromise devices and networks. Types include viruses, worms, trojans, ransomware, and spyware. Each has different methods of infection and damage.',
    whyItMatters: 'Malware can steal your data, encrypt your files for ransom, spy on your activities, or turn your device into part of a botnet for criminal activities.',
    examples: ['WannaCry ransomware affecting hospitals', 'Emotet banking trojan', 'Cryptominers hijacking device resources', 'Keyloggers capturing passwords'],
    tips: ['Use reputable antivirus software', 'Never download from untrusted sources', 'Scan USB drives before opening', 'Keep all software updated', 'Be cautious with email attachments'],
    quiz: [
      { question: 'What is ransomware?', options: ['Free software', 'Malware that encrypts files for payment', 'Antivirus software', 'A firewall'], correctIndex: 1 },
      { question: 'How do most viruses spread?', options: ['Through air', 'Via infected files or links', 'By looking at a screen', 'Through keyboards'], correctIndex: 1 },
      { question: 'What is a trojan horse in computing?', options: ['A fast computer', 'Malware disguised as legitimate software', 'A type of CPU', 'An antivirus'], correctIndex: 1 },
      { question: 'Which is NOT a type of malware?', options: ['Spyware', 'Ransomware', 'Fireware', 'Adware'], correctIndex: 2 },
      { question: 'True or False: Macs cannot get viruses.', options: ['True', 'False - all systems can be infected'], correctIndex: 1 },
    ],
  },
  {
    id: 'vpn-firewall',
    title: 'VPN & Firewall Basics',
    description: 'Learn about network protection tools',
    content: 'VPNs (Virtual Private Networks) encrypt your internet connection and mask your IP address. Firewalls monitor and control network traffic based on security rules. Together, they form essential network protection.',
    whyItMatters: 'Without these protections, your internet activity can be monitored, and your devices are more vulnerable to network-based attacks.',
    examples: ['Using VPN on public WiFi', 'Firewall blocking unauthorized access', 'Bypassing geographic restrictions safely', 'Corporate VPNs for remote work'],
    tips: ['Use VPN on public networks', 'Enable your firewall', 'Choose reputable VPN providers', 'Understand what a VPN does and does not protect', 'Configure firewall rules appropriately'],
    quiz: [
      { question: 'What does VPN stand for?', options: ['Very Private Network', 'Virtual Private Network', 'Virtual Public Network', 'Verified Private Net'], correctIndex: 1 },
      { question: 'What does a firewall do?', options: ['Heats the room', 'Monitors and controls network traffic', 'Speeds up internet', 'Stores passwords'], correctIndex: 1 },
      { question: 'When should you use a VPN?', options: ['Never', 'Only at home', 'On public WiFi networks', 'Only for gaming'], correctIndex: 2 },
      { question: 'True or False: A VPN makes you completely anonymous.', options: ['True', 'False - it provides privacy, not complete anonymity'], correctIndex: 1 },
      { question: 'Which is a benefit of using a VPN?', options: ['Faster internet always', 'Encrypted connection', 'Free software', 'Unlimited storage'], correctIndex: 1 },
    ],
  },
  {
    id: 'encryption',
    title: 'Encryption Basics',
    description: 'Understand how data protection works',
    content: 'Encryption is the process of converting data into a coded format that can only be read by someone with the decryption key. It protects data at rest (stored) and in transit (being sent).',
    whyItMatters: 'Encryption is the backbone of digital security. Without it, anyone who intercepts your data can read it. It protects everything from messages to financial transactions.',
    examples: ['HTTPS encrypting web traffic', 'End-to-end encryption in messaging apps', 'Encrypted hard drives', 'Secure email services'],
    tips: ['Use encrypted messaging apps', 'Enable device encryption', 'Look for HTTPS on websites', 'Encrypt sensitive files', 'Understand public vs private keys'],
    quiz: [
      { question: 'What is encryption?', options: ['Deleting data', 'Converting data to coded format', 'Copying files', 'Compressing data'], correctIndex: 1 },
      { question: 'What is needed to decrypt encrypted data?', options: ['A password manager', 'The decryption key', 'An antivirus', 'A firewall'], correctIndex: 1 },
      { question: 'Which messaging feature is most secure?', options: ['No encryption', 'Server-side encryption', 'End-to-end encryption', 'Basic encryption'], correctIndex: 2 },
      { question: 'True or False: Encryption slows down all devices significantly.', options: ['True', 'False - modern encryption is efficient'], correctIndex: 1 },
      { question: 'What does the "S" in HTTPS stand for?', options: ['Speed', 'Secure', 'Server', 'Simple'], correctIndex: 1 },
    ],
  },
  {
    id: 'advanced-firewall',
    title: 'Advanced Firewalls & Network Defense',
    description: 'Deep dive into network security',
    content: 'Advanced firewall concepts include stateful inspection, intrusion detection/prevention systems (IDS/IPS), network segmentation, and zero-trust architecture. These work together to create defense-in-depth.',
    whyItMatters: 'As attacks become more sophisticated, basic defenses are not enough. Understanding advanced concepts helps you implement robust security measures.',
    examples: ['Next-generation firewalls (NGFW)', 'Intrusion detection systems alerting on attacks', 'Network segmentation preventing lateral movement', 'Zero-trust requiring continuous verification'],
    tips: ['Implement defense-in-depth', 'Monitor network traffic', 'Segment sensitive systems', 'Keep security software updated', 'Conduct regular security audits'],
    quiz: [
      { question: 'What is an IDS?', options: ['Internet Download Service', 'Intrusion Detection System', 'Internal Data Storage', 'Integrated Defense System'], correctIndex: 1 },
      { question: 'What is network segmentation?', options: ['Breaking the network', 'Dividing network into isolated sections', 'Connecting all devices', 'Wireless networking'], correctIndex: 1 },
      { question: 'What is zero-trust architecture?', options: ['Trusting everyone', 'Never verify users', 'Always verify, never trust by default', 'No security needed'], correctIndex: 2 },
      { question: 'What does defense-in-depth mean?', options: ['One strong firewall', 'Multiple layers of security', 'Deep sea defense', 'Password protection only'], correctIndex: 1 },
      { question: 'True or False: IPS can block attacks automatically.', options: ['True', 'False - only IDS can'], correctIndex: 0 },
    ],
  },
];

const Academy: React.FC = () => {
  const [selectedModule, setSelectedModule] = useState<Module | null>(null);
  const [showQuiz, setShowQuiz] = useState(false);
  const [quizAnswers, setQuizAnswers] = useState<Record<number, number>>({});
  const [quizSubmitted, setQuizSubmitted] = useState(false);

  const handleStartQuiz = () => {
    setShowQuiz(true);
    setQuizAnswers({});
    setQuizSubmitted(false);
  };

  const handleAnswer = (questionIndex: number, optionIndex: number) => {
    if (!quizSubmitted) {
      setQuizAnswers({ ...quizAnswers, [questionIndex]: optionIndex });
    }
  };

  const handleSubmitQuiz = () => {
    setQuizSubmitted(true);
  };

  const getScore = () => {
    if (!selectedModule) return 0;
    let correct = 0;
    selectedModule.quiz.forEach((q, i) => {
      if (quizAnswers[i] === q.correctIndex) correct++;
    });
    return correct;
  };

  if (selectedModule) {
    return (
      <div className="min-h-screen py-8 px-4">
        <div className="container mx-auto max-w-4xl">
          {/* Back Button */}
          <Button
            variant="ghost"
            onClick={() => { setSelectedModule(null); setShowQuiz(false); }}
            className="mb-6"
          >
            ← Back to Modules
          </Button>

          {!showQuiz ? (
            // Module Content
            <div className="space-y-8 animate-fade-in-up">
              <div className="glass-card p-8">
                <div className="flex items-center gap-3 mb-6">
                  <BookOpen className="w-8 h-8 text-primary" />
                  <h1 className="font-display text-3xl font-bold text-gradient-primary">
                    {selectedModule.title}
                  </h1>
                </div>

                <div className="space-y-6">
                  <div>
                    <h2 className="font-display text-xl font-semibold mb-3">Overview</h2>
                    <p className="text-muted-foreground leading-relaxed">{selectedModule.content}</p>
                  </div>

                  <div className="p-4 bg-primary/10 rounded-lg border border-primary/30">
                    <h3 className="font-display font-semibold mb-2 text-primary">Why It Matters</h3>
                    <p className="text-muted-foreground">{selectedModule.whyItMatters}</p>
                  </div>

                  <div>
                    <h3 className="font-display text-lg font-semibold mb-3">Real-World Examples</h3>
                    <ul className="space-y-2">
                      {selectedModule.examples.map((example, i) => (
                        <li key={i} className="flex items-start gap-2 text-muted-foreground">
                          <ArrowRight className="w-4 h-4 mt-1 text-secondary shrink-0" />
                          {example}
                        </li>
                      ))}
                    </ul>
                  </div>

                  <div>
                    <h3 className="font-display text-lg font-semibold mb-3">Key Tips</h3>
                    <ul className="space-y-2">
                      {selectedModule.tips.map((tip, i) => (
                        <li key={i} className="flex items-start gap-2 text-muted-foreground">
                          <CheckCircle className="w-4 h-4 mt-1 text-accent shrink-0" />
                          {tip}
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>

              <Button variant="neon" size="lg" onClick={handleStartQuiz} className="w-full">
                Take Quiz ({selectedModule.quiz.length} Questions)
              </Button>
            </div>
          ) : (
            // Quiz
            <div className="space-y-6 animate-fade-in-up">
              <div className="glass-card p-6">
                <h2 className="font-display text-2xl font-bold mb-6 flex items-center gap-3">
                  <Trophy className="w-6 h-6 text-primary" />
                  {selectedModule.title} Quiz
                </h2>

                {!quizSubmitted ? (
                  <>
                    <div className="space-y-6">
                      {selectedModule.quiz.map((q, qIndex) => (
                        <div key={qIndex} className="p-4 bg-muted/30 rounded-lg">
                          <p className="font-medium mb-4">{qIndex + 1}. {q.question}</p>
                          <div className="space-y-2">
                            {q.options.map((option, oIndex) => (
                              <button
                                key={oIndex}
                                onClick={() => handleAnswer(qIndex, oIndex)}
                                className={cn(
                                  "w-full text-left p-3 rounded-lg border transition-all",
                                  quizAnswers[qIndex] === oIndex
                                    ? "border-primary bg-primary/20"
                                    : "border-border/50 hover:border-primary/50"
                                )}
                              >
                                {option}
                              </button>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>

                    <Button
                      variant="neon"
                      size="lg"
                      className="w-full mt-6"
                      onClick={handleSubmitQuiz}
                      disabled={Object.keys(quizAnswers).length !== selectedModule.quiz.length}
                    >
                      Submit Quiz
                    </Button>
                  </>
                ) : (
                  // Quiz Results
                  <div className="space-y-6">
                    <div className="text-center p-6 bg-muted/30 rounded-lg">
                      <Trophy className="w-12 h-12 mx-auto mb-4 text-primary" />
                      <p className="font-display text-4xl font-bold text-gradient-primary mb-2">
                        {getScore()} / {selectedModule.quiz.length}
                      </p>
                      <p className="text-muted-foreground">
                        {getScore() === selectedModule.quiz.length ? 'Perfect Score!' : 
                         getScore() >= selectedModule.quiz.length * 0.7 ? 'Great Job!' : 
                         'Keep Learning!'}
                      </p>
                      <Progress value={(getScore() / selectedModule.quiz.length) * 100} className="h-3 mt-4" />
                    </div>

                    {/* Show answers */}
                    <div className="space-y-4">
                      {selectedModule.quiz.map((q, qIndex) => (
                        <div key={qIndex} className="p-4 bg-muted/30 rounded-lg">
                          <p className="font-medium mb-3">{qIndex + 1}. {q.question}</p>
                          <div className="space-y-2">
                            {q.options.map((option, oIndex) => (
                              <div
                                key={oIndex}
                                className={cn(
                                  "p-3 rounded-lg border flex items-center gap-2",
                                  oIndex === q.correctIndex && "border-green-500 bg-green-500/20",
                                  quizAnswers[qIndex] === oIndex && oIndex !== q.correctIndex && "border-destructive bg-destructive/20"
                                )}
                              >
                                {oIndex === q.correctIndex ? (
                                  <CheckCircle className="w-4 h-4 text-green-500" />
                                ) : quizAnswers[qIndex] === oIndex ? (
                                  <XCircle className="w-4 h-4 text-destructive" />
                                ) : null}
                                {option}
                              </div>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="flex gap-4">
                      <Button variant="neon-outline" onClick={() => setShowQuiz(false)} className="flex-1">
                        Review Module
                      </Button>
                      <Button variant="neon" onClick={handleStartQuiz} className="flex-1">
                        <RotateCcw className="w-4 h-4 mr-2" />
                        Retake Quiz
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen py-8 px-4">
      <div className="container mx-auto max-w-7xl">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="font-display text-4xl lg:text-5xl font-bold text-gradient-primary mb-4">
            Learning Academy
          </h1>
          <p className="text-muted-foreground max-w-2xl mx-auto">
            Master cybersecurity through 8 comprehensive modules. Each includes lessons, examples, and quizzes.
          </p>
        </div>

        {/* Modules Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {modules.map((module, index) => (
            <button
              key={module.id}
              onClick={() => setSelectedModule(module)}
              className="glass-card-hover p-6 text-left group"
              style={{ animationDelay: `${index * 0.1}s` }}
            >
              <div className="w-10 h-10 rounded-lg bg-primary/20 text-primary flex items-center justify-center mb-4 group-hover:bg-primary group-hover:text-primary-foreground transition-all duration-300">
                <span className="font-display font-bold">{index + 1}</span>
              </div>
              <h3 className="font-display font-semibold text-lg mb-2">{module.title}</h3>
              <p className="text-sm text-muted-foreground mb-4">{module.description}</p>
              <div className="flex items-center text-primary text-sm font-medium">
                Start Learning <ArrowRight className="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" />
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Academy;
