import React, { useState } from 'react';
import {
  Compass,
  ArrowRight,
  RotateCcw,
  Sparkles,
  CheckCircle2,
  Calendar,
  Award,
  ChevronRight,
  MessageCircle,
  FileText,
  Clock,
  Layers,
  Zap,
} from 'lucide-react';
import { Container, Eyebrow } from './Ui';
import { Reveal } from './Brand';
import { findCourseBySlug, COURSES, SUBJECTS, ZiteCourse } from '../data/courses';

interface PathwayAdvisorProps {
  onNavigate: (path: string) => void;
  onOpenSyllabus?: (course: ZiteCourse) => void;
  isModal?: boolean;
  onClose?: () => void;
}

interface QuestionStep {
  title: string;
  subtitle: string;
  options: {
    id: string;
    label: string;
    description: string;
    icon?: string;
  }[];
}

export function PathwayAdvisor({
  onNavigate,
  onOpenSyllabus,
  isModal = false,
  onClose,
}: PathwayAdvisorProps) {
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [background, setBackground] = useState<string>('');
  const [interest, setInterest] = useState<string>('');
  const [commitment, setCommitment] = useState<string>('');

  const steps: QuestionStep[] = [
    {
      title: 'What is your current background and experience?',
      subtitle: 'Select the option that best describes your starting point.',
      options: [
        {
          id: 'beginner',
          label: 'Complete Beginner / Non-Technical',
          description: 'No prior coding or IT experience; switching into digital skills from another field.',
        },
        {
          id: 'student',
          label: 'Student or Recent Graduate',
          description: 'Have foundational computer literacy; want job-ready skills that employers demand.',
        },
        {
          id: 'it_support',
          label: 'IT Support / Hardware / Sysadmin',
          description: 'Working in tech support or administration; looking to upskill into Cloud or DevOps.',
        },
        {
          id: 'freelancer',
          label: 'Administrative / Freelance / Creative',
          description: 'Looking to earn independent or remote income working with global online clients.',
        },
      ],
    },
    {
      title: 'What field or career direction excites you most?',
      subtitle: 'Choose your preferred specialization area.',
      options: [
        {
          id: 'cloud',
          label: 'Cloud Computing & Infrastructure',
          description: 'Work with AWS, Google Cloud, or Azure to deploy and manage modern systems.',
        },
        {
          id: 'ai',
          label: 'Artificial Intelligence & Data',
          description: 'Explore AI capabilities, prompt engineering, data annotation, and data science.',
        },
        {
          id: 'security',
          label: 'Cybersecurity, Linux & Networks',
          description: 'Protect IT systems, troubleshoot Cisco networks, and master Linux environments.',
        },
        {
          id: 'work',
          label: 'Remote Virtual Assistance & Work Readiness',
          description: 'Deliver executive administrative support, freelance management, and digital services.',
        },
      ],
    },
    {
      title: 'What weekly time commitment works best for you?',
      subtitle: 'All programmes are delivered live online with evening and weekend flexibility.',
      options: [
        {
          id: 'evenings',
          label: 'Flexible Evenings (6–8 hrs / week)',
          description: 'Ideal if you work full-time or attend university during standard day hours.',
        },
        {
          id: 'weekends',
          label: 'Weekend Focused (Live Sat/Sun Practicals)',
          description: 'Concentrated live instruction on weekends with weekly WhatsApp check-ins.',
        },
        {
          id: 'intensive',
          label: 'Fast-Track Intensive (12+ hrs / week)',
          description: 'Committed to fast career transition with extensive daily lab practice.',
        },
      ],
    },
  ];

  // Logic to determine recommended courses based on user inputs
  const getRecommendations = (): { primary: ZiteCourse; secondary: ZiteCourse; matchReason: string } => {
    let primarySlug = 'aws-cloud-practitioner-preparation';
    let secondarySlug = 'virtual-assistant-training';
    let matchReason = 'A versatile foundation tailored for high market demand.';

    if (interest === 'cloud') {
      if (background === 'it_support' || background === 'student') {
        primarySlug = 'aws-solutions-architect-associate-preparation';
        secondarySlug = 'aws-cloud-practitioner-preparation';
        matchReason = 'Your technical baseline positions you perfectly to target the industry-standard AWS Solutions Architect Associate credential.';
      } else {
        primarySlug = 'aws-cloud-practitioner-preparation';
        secondarySlug = 'google-cloud-platform-training';
        matchReason = 'The AWS Cloud Practitioner pathway introduces core cloud fundamentals without requiring coding experience.';
      }
    } else if (interest === 'ai') {
      if (background === 'beginner' || background === 'freelancer') {
        primarySlug = 'artificial-intelligence';
        secondarySlug = 'image-annotation-basics';
        matchReason = 'Provides practical AI literacy and data annotation skills for immediate remote opportunities.';
      } else {
        primarySlug = 'aws-ai-practitioner-preparation';
        secondarySlug = 'data-science';
        matchReason = 'Combines modern generative AI and cloud-native machine learning principles with official AWS certification alignment.';
      }
    } else if (interest === 'security') {
      if (background === 'it_support') {
        primarySlug = 'cybersecurity-courses';
        secondarySlug = 'cisco-networking';
        matchReason = 'Builds on your IT knowledge with hands-on threat defense, network security analysis, and incident response.';
      } else {
        primarySlug = 'linux-and-networking-fundamentals';
        secondarySlug = 'cybersecurity-courses';
        matchReason = 'Equips you with essential Linux command-line confidence and networking fundamentals before advancing into cyber defense.';
      }
    } else if (interest === 'work') {
      if (background === 'freelancer' || background === 'beginner') {
        primarySlug = 'virtual-assistant-training';
        secondarySlug = 'online-work-readiness';
        matchReason = 'Covers real client administrative workflows, digital workspace tools, and communication standards for remote earnings.';
      } else {
        primarySlug = 'online-work-readiness';
        secondarySlug = 'communication-skills-for-corporate-teams';
        matchReason = 'Prepares you to structure and pitch your digital skills to global clients with confidence.';
      }
    }

    const primary = findCourseBySlug(primarySlug) || COURSES[0];
    const secondary = findCourseBySlug(secondarySlug) || COURSES[1];

    return { primary, secondary, matchReason };
  };

  const handleSelectOption = (optionId: string) => {
    if (currentStep === 0) {
      setBackground(optionId);
      setCurrentStep(1);
    } else if (currentStep === 1) {
      setInterest(optionId);
      setCurrentStep(2);
    } else if (currentStep === 2) {
      setCommitment(optionId);
      setCurrentStep(3); // Result step
    }
  };

  const handleReset = () => {
    setCurrentStep(0);
    setBackground('');
    setInterest('');
    setCommitment('');
  };

  const isCompleted = currentStep === 3;
  const { primary, secondary, matchReason } = isCompleted ? getRecommendations() : { primary: COURSES[0], secondary: COURSES[1], matchReason: '' };

  const content = (
    <div className="bg-card rounded-3xl border border-border shadow-xl overflow-hidden">
      {/* Header Bar */}
      <div className="p-6 md:p-8 bg-gradient-to-r from-primary/10 via-accent/10 to-transparent border-b border-border flex items-start justify-between gap-4">
        <div>
          <div className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-primary bg-primary/10 px-3 py-1 rounded-full">
            <Compass className="h-3.5 w-3.5" />
            <span>Interactive Course Advisor</span>
          </div>
          <h2 className="text-2xl sm:text-3xl font-bold mt-2 text-foreground">
            {isCompleted ? 'Your Personalized Learning Pathway' : 'Find Your Ideal Learning Pathway'}
          </h2>
          <p className="text-xs sm:text-sm text-muted-foreground mt-1 max-w-xl">
            {isCompleted
              ? 'Based on your background and career goals, here are the top-recommended programmes at PANIA.'
              : 'Answer 3 quick questions (takes under 60 seconds) to receive tailored programme recommendations.'}
          </p>
        </div>

        {isCompleted && (
          <button
            onClick={handleReset}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-border bg-card hover:bg-secondary text-xs font-semibold text-muted-foreground hover:text-foreground transition cursor-pointer shrink-0"
          >
            <RotateCcw className="h-3.5 w-3.5" />
            <span>Restart</span>
          </button>
        )}
      </div>

      {/* Step Progress Bar (when answering questions) */}
      {!isCompleted && (
        <div className="px-6 md:px-8 pt-4 pb-2 border-b border-border/60 bg-secondary/30 flex items-center justify-between text-xs">
          <div className="flex items-center gap-2">
            {[0, 1, 2].map((s) => (
              <span
                key={s}
                className={`h-2 transition-all rounded-full ${
                  currentStep === s
                    ? 'w-8 bg-primary'
                    : currentStep > s
                    ? 'w-4 bg-teal'
                    : 'w-4 bg-border'
                }`}
              />
            ))}
          </div>
          <span className="text-muted-foreground font-semibold">
            Step {currentStep + 1} of 3
          </span>
        </div>
      )}

      {/* Main Interactive Body */}
      <div className="p-6 md:p-8">
        {!isCompleted ? (
          <div>
            <h3 className="text-lg sm:text-xl font-bold text-foreground">
              {steps[currentStep].title}
            </h3>
            <p className="text-xs sm:text-sm text-muted-foreground mt-1">
              {steps[currentStep].subtitle}
            </p>

            <div className="grid gap-3.5 sm:grid-cols-2 mt-6">
              {steps[currentStep].options.map((opt) => (
                <button
                  key={opt.id}
                  onClick={() => handleSelectOption(opt.id)}
                  className="group text-left p-5 rounded-2xl border border-border bg-card hover:border-primary hover:bg-primary/5 transition-all shadow-xs cursor-pointer flex flex-col justify-between"
                >
                  <div>
                    <h4 className="font-bold text-sm sm:text-base text-foreground group-hover:text-primary transition-colors">
                      {opt.label}
                    </h4>
                    <p className="text-xs text-muted-foreground mt-1.5 leading-relaxed">
                      {opt.description}
                    </p>
                  </div>

                  <div className="mt-4 flex items-center gap-1 text-xs font-bold text-primary opacity-0 group-hover:opacity-100 transition-opacity">
                    <span>Select this option</span>
                    <ChevronRight className="h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform" />
                  </div>
                </button>
              ))}
            </div>

            {currentStep > 0 && (
              <button
                onClick={() => setCurrentStep((prev) => prev - 1)}
                className="mt-6 text-xs text-muted-foreground hover:text-foreground font-semibold underline cursor-pointer"
              >
                ← Back to previous question
              </button>
            )}
          </div>
        ) : (
          /* Recommendation Results Screen */
          <div className="space-y-8">
            {/* Why this matches banner */}
            <div className="p-4 rounded-2xl bg-teal/10 border border-teal/20 flex items-start gap-3">
              <Sparkles className="h-5 w-5 text-teal shrink-0 mt-0.5" />
              <div>
                <h4 className="font-bold text-xs uppercase tracking-wider text-teal">
                  Advisor Match Rationale
                </h4>
                <p className="text-xs sm:text-sm text-foreground mt-0.5 leading-relaxed font-medium">
                  {matchReason}
                </p>
              </div>
            </div>

            {/* Recommendation Cards Grid */}
            <div className="grid gap-6 md:grid-cols-2">
              {/* Primary Match Card */}
              <div className="rounded-3xl border-2 border-primary bg-primary/5 p-6 flex flex-col justify-between shadow-md relative overflow-hidden">
                <div className="absolute top-0 right-0 bg-primary text-primary-foreground text-[10px] font-bold px-3 py-1 rounded-bl-xl uppercase tracking-wider">
                  Top Recommended Match
                </div>

                <div>
                  <span className="text-xs font-bold text-primary uppercase tracking-wider block">
                    {SUBJECTS[primary.subject].label} · {primary.provider}
                  </span>
                  <h3 className="text-xl sm:text-2xl font-bold mt-2 text-foreground">
                    {primary.title}
                  </h3>
                  <p className="text-xs sm:text-sm text-muted-foreground mt-2 leading-relaxed">
                    {primary.who}
                  </p>

                  <div className="mt-4 space-y-2 text-xs">
                    <div className="flex items-center gap-2 text-foreground font-medium">
                      <CheckCircle2 className="h-4 w-4 text-teal shrink-0" />
                      <span>{primary.outcomes[0]}</span>
                    </div>
                    <div className="flex items-center gap-2 text-foreground font-medium">
                      <CheckCircle2 className="h-4 w-4 text-teal shrink-0" />
                      <span>{primary.outcomes[1]}</span>
                    </div>
                  </div>
                </div>

                <div className="mt-6 pt-4 border-t border-primary/20 space-y-2.5">
                  <button
                    onClick={() => onNavigate(`/programmes/${primary.slug}`)}
                    className="w-full py-3 px-4 rounded-xl bg-primary text-primary-foreground text-xs font-bold hover:opacity-90 transition flex items-center justify-center gap-2 shadow-xs cursor-pointer"
                  >
                    <span>View Programme Details</span>
                    <ArrowRight className="h-4 w-4" />
                  </button>

                  <div className="grid grid-cols-2 gap-2">
                    {onOpenSyllabus && (
                      <button
                        onClick={() => onOpenSyllabus(primary)}
                        className="py-2.5 px-3 rounded-xl border border-border bg-card hover:bg-secondary text-xs font-semibold text-foreground transition flex items-center justify-center gap-1.5 cursor-pointer"
                      >
                        <FileText className="h-3.5 w-3.5 text-primary" />
                        <span>Syllabus</span>
                      </button>
                    )}

                    <a
                      href={`https://wa.me/254101936893?text=Hello%20PANIA%2C%20the%20Advisor%20recommended%20${encodeURIComponent(
                        primary.title
                      )}.%20I%20would%20like%20to%20know%20more.`}
                      target="_blank"
                      rel="noreferrer"
                      className="py-2.5 px-3 rounded-xl bg-teal text-white text-xs font-semibold hover:opacity-90 transition flex items-center justify-center gap-1.5 cursor-pointer"
                    >
                      <MessageCircle className="h-3.5 w-3.5" />
                      <span>WhatsApp</span>
                    </a>
                  </div>
                </div>
              </div>

              {/* Secondary / Alternative Match Card */}
              <div className="rounded-3xl border border-border bg-card p-6 flex flex-col justify-between shadow-xs">
                <div>
                  <span className="text-xs font-bold text-muted-foreground uppercase tracking-wider block">
                    Strong Alternative · {secondary.provider}
                  </span>
                  <h3 className="text-xl sm:text-2xl font-bold mt-2 text-foreground">
                    {secondary.title}
                  </h3>
                  <p className="text-xs sm:text-sm text-muted-foreground mt-2 leading-relaxed">
                    {secondary.who}
                  </p>

                  <div className="mt-4 space-y-2 text-xs">
                    <div className="flex items-center gap-2 text-foreground font-medium">
                      <CheckCircle2 className="h-4 w-4 text-muted-foreground shrink-0" />
                      <span>{secondary.outcomes[0]}</span>
                    </div>
                    <div className="flex items-center gap-2 text-foreground font-medium">
                      <CheckCircle2 className="h-4 w-4 text-muted-foreground shrink-0" />
                      <span>{secondary.outcomes[1]}</span>
                    </div>
                  </div>
                </div>

                <div className="mt-6 pt-4 border-t border-border space-y-2.5">
                  <button
                    onClick={() => onNavigate(`/programmes/${secondary.slug}`)}
                    className="w-full py-3 px-4 rounded-xl border border-border bg-secondary/50 hover:bg-secondary text-foreground text-xs font-bold transition flex items-center justify-center gap-2 cursor-pointer"
                  >
                    <span>View Secondary Match</span>
                    <ArrowRight className="h-4 w-4" />
                  </button>

                  {onOpenSyllabus && (
                    <button
                      onClick={() => onOpenSyllabus(secondary)}
                      className="w-full py-2.5 px-3 rounded-xl border border-border bg-card hover:bg-secondary text-xs font-semibold text-muted-foreground hover:text-foreground transition flex items-center justify-center gap-1.5 cursor-pointer"
                    >
                      <FileText className="h-3.5 w-3.5" />
                      <span>Download Syllabus</span>
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* Bottom Cohort Notice & Direct Guidance link */}
            <div className="p-4 rounded-2xl bg-secondary/40 border border-border flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-muted-foreground">
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-accent shrink-0" />
                <span>
                  Next online cohort commences on the <strong>first Monday of next month</strong>.
                </span>
              </div>
              <button
                onClick={() => onNavigate('/contact?mode=guidance')}
                className="font-bold text-primary hover:underline cursor-pointer whitespace-nowrap"
              >
                Speak with an Academic Advisor →
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  if (isModal) {
    return (
      <div
        className="fixed inset-0 z-50 overflow-y-auto bg-black/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6"
        role="dialog"
        aria-modal="true"
      >
        <div className="w-full max-w-3xl relative">
          {onClose && (
            <button
              onClick={onClose}
              className="absolute top-4 right-4 z-10 p-2 rounded-full bg-card/80 text-muted-foreground hover:text-foreground cursor-pointer shadow-xs"
              aria-label="Close advisor"
            >
              ✕
            </button>
          )}
          {content}
        </div>
      </div>
    );
  }

  return (
    <section className="py-16 bg-secondary/20 border-b border-border" id="advisor">
      <Container>
        <Reveal>
          {content}
        </Reveal>
      </Container>
    </section>
  );
}
