import React, { useState } from 'react';
import {
  X,
  Plus,
  Scale,
  Award,
  Layers,
  Briefcase,
  FolderGit2,
  Calendar,
  Clock,
  ArrowRight,
  Download,
  Trash2,
  ExternalLink,
  Sparkles,
  ChevronRight,
  Users,
  CheckCircle2,
  HelpCircle,
  Printer,
  Share2,
  Check
} from 'lucide-react';
import { useComparison } from '../context/ComparisonContext';
import { COURSES, ZiteCourse, SUBJECTS, findCourseBySlug } from '../data/courses';
import {
  COURSE_COMPARISON_DATA,
  getCourseComparisonDetails,
  COMPARISON_PRESETS,
  ComparisonPreset,
} from '../data/courseComparisonData';
import { getCohortForCourse } from '../data/cohorts';
import { Eyebrow } from './Ui';

interface ComparisonDrawerProps {
  onNavigate: (path: string) => void;
  onOpenSyllabus?: (courseSlug?: string) => void;
}

export function ComparisonDrawer({ onNavigate, onOpenSyllabus }: ComparisonDrawerProps) {
  const {
    selectedSlugs,
    drawerOpen,
    setDrawerOpen,
    removeCourse,
    addCourse,
    clearAll,
    loadPreset,
  } = useComparison();

  const [courseSelectorOpenForIndex, setCourseSelectorOpenForIndex] = useState<number | null>(null);
  const [copiedLink, setCopiedLink] = useState(false);
  const [copyError, setCopyError] = useState(false);
  const modalRef = React.useRef<HTMLDivElement>(null);
  const previousActiveElement = React.useRef<HTMLElement | null>(null);

  // Body scroll lock & Escape listener & Focus management
  React.useEffect(() => {
    if (!drawerOpen) return;

    previousActiveElement.current = document.activeElement as HTMLElement;
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    // Focus close button or container
    if (modalRef.current) {
      modalRef.current.focus();
    }

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setDrawerOpen(false);
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener('keydown', handleKeyDown);
      if (previousActiveElement.current && typeof previousActiveElement.current.focus === 'function') {
        previousActiveElement.current.focus();
      }
    };
  }, [drawerOpen, setDrawerOpen]);

  if (!drawerOpen) return null;

  const selectedCourses: ZiteCourse[] = selectedSlugs
    .map((slug) => findCourseBySlug(slug))
    .filter((c): c is ZiteCourse => Boolean(c));

  const availableCoursesToAdd = COURSES.filter(
    (course) => !selectedSlugs.includes(course.slug)
  );

  const handleShareOrCopy = async () => {
    const url = `${window.location.origin}/#/programmes?compare=${selectedSlugs.join(',')}`;
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(url);
        setCopiedLink(true);
        setTimeout(() => setCopiedLink(false), 2500);
      } else {
        // Fallback
        const textarea = document.createElement('textarea');
        textarea.value = url;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        setCopiedLink(true);
        setTimeout(() => setCopiedLink(false), 2500);
      }
    } catch {
      setCopyError(true);
      setTimeout(() => setCopyError(false), 3000);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="comparison-drawer-title"
      className="fixed inset-0 z-50 overflow-y-auto bg-black/70 backdrop-blur-sm animate-in fade-in duration-200 flex flex-col justify-end lg:justify-center p-0 lg:p-6"
    >
      {/* Drawer / Modal Container */}
      <div
        ref={modalRef}
        tabIndex={-1}
        className="bg-card w-full max-w-7xl mx-auto rounded-t-3xl lg:rounded-3xl shadow-2xl border border-border flex flex-col max-h-[92vh] overflow-hidden focus:outline-none"
      >
        {/* Header Bar */}
        <div className="p-4 sm:p-6 border-b border-border flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 bg-secondary/30">
          <div className="flex items-center gap-3">
            <span className="w-10 h-10 rounded-2xl bg-primary text-primary-foreground flex items-center justify-center shadow-xs">
              <Scale className="w-5 h-5" aria-hidden="true" />
            </span>
            <div>
              <div className="flex items-center gap-2">
                <h2 id="comparison-drawer-title" className="text-xl sm:text-2xl font-bold tracking-tight text-foreground">
                  Side-by-Side Track Comparison
                </h2>
                <span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20">
                  {selectedCourses.length} of 3 tracks
                </span>
              </div>
              <p className="text-xs text-muted-foreground mt-0.5">
                Evaluate prerequisites, vendor exams, hands-on capstones, and career destinations side-by-side.
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2 self-end sm:self-auto">
            <button
              onClick={handlePrint}
              className="inline-flex items-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded-full text-xs font-semibold border border-border bg-card hover:bg-secondary transition text-muted-foreground hover:text-foreground cursor-pointer"
              title="Print or Save PDF"
            >
              <Printer className="w-3.5 h-3.5 text-primary" aria-hidden="true" />
              <span className="hidden sm:inline">Print / PDF</span>
            </button>

            <button
              onClick={handleShareOrCopy}
              className="inline-flex items-center gap-1.5 min-h-[36px] px-3.5 py-1.5 rounded-full text-xs font-semibold border border-border bg-card hover:bg-secondary transition text-muted-foreground hover:text-foreground cursor-pointer"
              title="Copy shareable link"
            >
              {copiedLink ? (
                <>
                  <Check className="w-3.5 h-3.5 text-emerald-600" aria-hidden="true" />
                  <span className="text-emerald-700 font-bold">Link Copied!</span>
                </>
              ) : copyError ? (
                <span className="text-rose-600 font-bold">Copy Failed</span>
              ) : (
                <>
                  <Share2 className="w-3.5 h-3.5 text-teal" aria-hidden="true" />
                  <span className="hidden sm:inline">Share</span>
                </>
              )}
            </button>

            {selectedCourses.length > 0 && (
              <button
                onClick={clearAll}
                className="inline-flex items-center gap-1 min-h-[36px] px-3 py-1.5 rounded-full text-xs font-semibold text-rose-600 hover:bg-rose-500/10 transition cursor-pointer"
                title="Clear all compared courses"
              >
                <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                <span className="hidden sm:inline">Clear all</span>
              </button>
            )}

            <button
              onClick={() => setDrawerOpen(false)}
              className="w-10 h-10 rounded-full bg-secondary hover:bg-muted text-foreground flex items-center justify-center transition cursor-pointer"
              aria-label="Close comparison drawer"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Quick Presets Bar */}
        <div className="px-4 sm:px-6 py-2.5 bg-secondary/50 border-b border-border flex items-center gap-2 overflow-x-auto no-scrollbar text-xs">
          <span className="text-muted-foreground font-semibold shrink-0 flex items-center gap-1">
            <Sparkles className="w-3.5 h-3.5 text-accent" />
            Quick Presets:
          </span>
          {COMPARISON_PRESETS.map((preset) => (
            <button
              key={preset.id}
              onClick={() => loadPreset(preset.id)}
              className="shrink-0 px-3 py-1 rounded-full bg-card hover:bg-secondary border border-border text-foreground text-xs font-medium transition cursor-pointer flex items-center gap-1.5"
            >
              <span>{preset.title}</span>
            </button>
          ))}
        </div>

        {/* Comparison Content Table / Grid */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-6">
          {selectedCourses.length === 0 ? (
            <div className="py-16 text-center space-y-4 max-w-md mx-auto">
              <span className="w-16 h-16 rounded-3xl bg-secondary mx-auto flex items-center justify-center text-muted-foreground">
                <Scale className="w-8 h-8" />
              </span>
              <h3 className="text-lg font-bold">No Courses Selected for Comparison</h3>
              <p className="text-xs text-muted-foreground">
                Select any 2 or 3 courses from the catalogue to compare prerequisites, vendor certifications, capstones, and career tracks.
              </p>
              <div className="pt-2 flex flex-wrap justify-center gap-2">
                {COMPARISON_PRESETS.slice(0, 3).map((p) => (
                  <button
                    key={p.id}
                    onClick={() => loadPreset(p.id)}
                    className="px-3.5 py-1.5 rounded-full text-xs font-bold bg-primary text-primary-foreground hover:opacity-90 cursor-pointer"
                  >
                    Compare: {p.title}
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              {/* Columns Header (Course Cards) */}
              <div
                className={`grid gap-4 ${
                  selectedCourses.length === 1
                    ? 'grid-cols-1 max-w-xl mx-auto'
                    : selectedCourses.length === 2
                    ? 'grid-cols-1 md:grid-cols-2'
                    : 'grid-cols-1 md:grid-cols-3'
                }`}
              >
                {selectedCourses.map((course) => {
                  const meta = SUBJECTS[course.subject];
                  const details = getCourseComparisonDetails(course);
                  const cohort = getCohortForCourse(course.slug);

                  return (
                    <div
                      key={course.code}
                      className="bg-card rounded-2xl border border-border p-4 sm:p-5 flex flex-col justify-between shadow-xs relative group"
                    >
                      <div>
                        {/* Provider & Remove button */}
                        <div className="flex items-center justify-between gap-2 mb-2">
                          <span
                            className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full ${meta.bgSoft} ${meta.textColor}`}
                          >
                            {course.provider} · {meta.short}
                          </span>
                          <button
                            onClick={() => removeCourse(course.slug)}
                            className="p-1 rounded-full text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition cursor-pointer"
                            title="Remove from comparison"
                          >
                            <X className="w-4 h-4" />
                          </button>
                        </div>

                        {/* Image Preview & Title */}
                        <div className="flex gap-3 items-start mt-2">
                          <img
                            src={course.image || meta.photo}
                            alt={course.title}
                            className="w-16 h-16 rounded-xl object-cover shrink-0 border border-border shadow-2xs"
                          />
                          <div>
                            <h3
                              onClick={() => {
                                setDrawerOpen(false);
                                onNavigate(`/programmes/${course.slug}`);
                              }}
                              className="font-bold text-sm sm:text-base text-foreground hover:text-primary transition-colors cursor-pointer line-clamp-2"
                            >
                              {course.title}
                            </h3>
                            <p className="text-xs text-muted-foreground mt-0.5 line-clamp-1 italic">
                              "{course.headline[0]} {course.headline[1]}"
                            </p>
                          </div>
                        </div>
                      </div>

                      {/* Header Quick CTA */}
                      <div className="mt-4 pt-3 border-t border-border flex items-center gap-2">
                        <button
                          onClick={() => {
                            setDrawerOpen(false);
                            onNavigate(`/contact?mode=learner&course=${course.slug}`);
                          }}
                          className="flex-1 py-2 px-3 rounded-xl text-xs font-bold bg-primary text-primary-foreground hover:opacity-90 transition text-center cursor-pointer shadow-2xs"
                        >
                          Enrol in Track
                        </button>
                        <button
                          onClick={() => {
                            if (onOpenSyllabus) onOpenSyllabus(course.slug);
                          }}
                          className="py-2 px-3 rounded-xl text-xs font-semibold border border-border bg-card hover:bg-secondary text-foreground transition cursor-pointer"
                          title="View Syllabus"
                        >
                          Syllabus
                        </button>
                      </div>
                    </div>
                  );
                })}

                {/* Add slot placeholder if fewer than 3 courses */}
                {selectedCourses.length < 3 && (
                  <div className="rounded-2xl border-2 border-dashed border-border/80 p-6 flex flex-col items-center justify-center text-center space-y-3 min-h-[180px] bg-secondary/20">
                    <span className="w-10 h-10 rounded-full bg-secondary text-muted-foreground flex items-center justify-center">
                      <Plus className="w-5 h-5" />
                    </span>
                    <div>
                      <p className="text-xs font-bold text-foreground">Add Another Track</p>
                      <p className="text-[11px] text-muted-foreground mt-0.5">
                        Compare up to 3 courses side-by-side
                      </p>
                    </div>

                    <div className="relative w-full max-w-xs">
                      <select
                        onChange={(e) => {
                          if (e.target.value) {
                            addCourse(e.target.value);
                            e.target.value = '';
                          }
                        }}
                        defaultValue=""
                        className="w-full text-xs font-semibold px-3 py-2 rounded-xl bg-card border border-border text-foreground cursor-pointer focus:ring-2 focus:ring-primary focus:outline-hidden"
                      >
                        <option value="" disabled>
                          + Select a course to compare...
                        </option>
                        {availableCoursesToAdd.map((c) => (
                          <option key={c.code} value={c.slug}>
                            {c.title} ({c.provider})
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
                )}
              </div>

              {/* SIDE-BY-SIDE COMPARISON SECTIONS */}
              <div className="space-y-4 pt-2">
                {/* 1. PREREQUISITE LEVEL BREAKDOWN */}
                <ComparisonSectionHeader
                  icon={<Layers className="w-4 h-4 text-primary" />}
                  title="1. Prerequisite Level & Background Needed"
                  subtitle="Does this track require previous coding or system administration, or is it open to absolute beginners?"
                />
                <div
                  className={`grid gap-4 ${
                    selectedCourses.length === 1
                      ? 'grid-cols-1 max-w-xl mx-auto'
                      : selectedCourses.length === 2
                      ? 'grid-cols-1 md:grid-cols-2'
                      : 'grid-cols-1 md:grid-cols-3'
                  }`}
                >
                  {selectedCourses.map((course) => {
                    const details = getCourseComparisonDetails(course);
                    const isBeginner = details.level.includes('Beginner');
                    return (
                      <div
                        key={course.code}
                        className="p-4 rounded-2xl bg-secondary/50 border border-border/70 space-y-2.5"
                      >
                        <div className="flex items-center gap-2">
                          <span
                            className={`text-xs font-bold px-2.5 py-1 rounded-full ${
                              isBeginner
                                ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20'
                                : 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/20'
                            }`}
                          >
                            {details.level}
                          </span>
                        </div>
                        <p className="text-xs text-foreground font-medium leading-relaxed">
                          {details.prerequisites}
                        </p>
                        <div className="text-[11px] text-muted-foreground pt-1 border-t border-border/40">
                          <strong>Best if you want to:</strong> {details.bestIfYouWantTo}
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* 2. TARGET VENDOR EXAMINATION */}
                <ComparisonSectionHeader
                  icon={<Award className="w-4 h-4 text-teal" />}
                  title="2. Target Vendor Examination & Credential"
                  subtitle="Which global industry standard or certifying body exam does this curriculum prepare you for?"
                />
                <div
                  className={`grid gap-4 ${
                    selectedCourses.length === 1
                      ? 'grid-cols-1 max-w-xl mx-auto'
                      : selectedCourses.length === 2
                      ? 'grid-cols-1 md:grid-cols-2'
                      : 'grid-cols-1 md:grid-cols-3'
                  }`}
                >
                  {selectedCourses.map((course) => {
                    const details = getCourseComparisonDetails(course);
                    return (
                      <div
                        key={course.code}
                        className="p-4 rounded-2xl bg-secondary/50 border border-border/70 space-y-2.5"
                      >
                        <div className="flex items-center justify-between">
                          <span className="text-[11px] font-bold px-2.5 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20">
                            {details.examBadge}
                          </span>
                          <span className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">
                            {details.examType}
                          </span>
                        </div>
                        <p className="text-xs font-bold text-foreground">
                          {details.targetExam}
                        </p>
                        <p className="text-[11px] text-muted-foreground leading-relaxed">
                          Instruction includes practice exam question walkthroughs, blueprint domain breakdowns, and timed quiz drills.
                        </p>
                      </div>
                    );
                  })}
                </div>

                {/* 3. HANDS-ON CAPSTONE PROJECT */}
                <ComparisonSectionHeader
                  icon={<FolderGit2 className="w-4 h-4 text-[#D5E64D]" />}
                  title="3. Hands-On Capstone Project & Deliverables"
                  subtitle="What concrete practical artifact or portfolio piece will you build to showcase to employers?"
                />
                <div
                  className={`grid gap-4 ${
                    selectedCourses.length === 1
                      ? 'grid-cols-1 max-w-xl mx-auto'
                      : selectedCourses.length === 2
                      ? 'grid-cols-1 md:grid-cols-2'
                      : 'grid-cols-1 md:grid-cols-3'
                  }`}
                >
                  {selectedCourses.map((course) => {
                    const details = getCourseComparisonDetails(course);
                    return (
                      <div
                        key={course.code}
                        className="p-4 rounded-2xl bg-secondary/50 border border-border/70 space-y-2.5"
                      >
                        <div className="space-y-1">
                          <span className="text-[11px] font-bold text-primary block">
                            Capstone Focus:
                          </span>
                          <p className="text-xs font-bold text-foreground">
                            {details.capstoneProject.title}
                          </p>
                        </div>
                        <p className="text-xs text-muted-foreground leading-relaxed">
                          {details.capstoneProject.description}
                        </p>
                        <div className="p-2.5 rounded-xl bg-card border border-border text-[11px] text-foreground">
                          <strong className="text-teal font-semibold">Verified Portfolio Deliverable:</strong>{' '}
                          {details.capstoneProject.deliverable}
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* 4. IDEAL CAREER DESTINATION */}
                <ComparisonSectionHeader
                  icon={<Briefcase className="w-4 h-4 text-ocean" />}
                  title="4. Ideal Career Destination & Market Demand"
                  subtitle="Which exact job titles, daily work settings, and hiring sectors recruit for this profile?"
                />
                <div
                  className={`grid gap-4 ${
                    selectedCourses.length === 1
                      ? 'grid-cols-1 max-w-xl mx-auto'
                      : selectedCourses.length === 2
                      ? 'grid-cols-1 md:grid-cols-2'
                      : 'grid-cols-1 md:grid-cols-3'
                  }`}
                >
                  {selectedCourses.map((course) => {
                    const details = getCourseComparisonDetails(course);
                    return (
                      <div
                        key={course.code}
                        className="p-4 rounded-2xl bg-secondary/50 border border-border/70 space-y-3"
                      >
                        <div>
                          <div className="flex items-center justify-between mb-1.5">
                            <span className="text-[11px] font-bold text-muted-foreground">
                              Target Job Titles:
                            </span>
                            <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
                              {details.careerDestination.marketDemand} Demand
                            </span>
                          </div>
                          <div className="flex flex-wrap gap-1.5">
                            {details.careerDestination.primaryRoles.map((role, idx) => (
                              <span
                                key={idx}
                                className="text-[11px] font-medium px-2 py-0.5 rounded-md bg-card border border-border text-foreground"
                              >
                                {role}
                              </span>
                            ))}
                          </div>
                        </div>

                        <div className="text-[11px] text-muted-foreground pt-1 border-t border-border/40">
                          <strong className="text-foreground">Work Setting:</strong>{' '}
                          {details.careerDestination.workSetting}
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* 5. TIME COMMITMENT, SCHEDULE & INTAKE STATUS */}
                <ComparisonSectionHeader
                  icon={<Clock className="w-4 h-4 text-stone-400" />}
                  title="5. Weekly Commitment, Duration & Confirmed Intake"
                  subtitle="How much time do you need to budget, and when is the next confirmed class launching?"
                />
                <div
                  className={`grid gap-4 ${
                    selectedCourses.length === 1
                      ? 'grid-cols-1 max-w-xl mx-auto'
                      : selectedCourses.length === 2
                      ? 'grid-cols-1 md:grid-cols-2'
                      : 'grid-cols-1 md:grid-cols-3'
                  }`}
                >
                  {selectedCourses.map((course) => {
                    const details = getCourseComparisonDetails(course);
                    const cohort = getCohortForCourse(course.slug);
                    return (
                      <div
                        key={course.code}
                        className="p-4 rounded-2xl bg-secondary/50 border border-border/70 space-y-2 text-xs"
                      >
                        <div className="flex justify-between items-center text-foreground font-semibold">
                          <span className="text-muted-foreground">Duration:</span>
                          <span>{details.typicalDuration}</span>
                        </div>
                        <div className="flex justify-between items-center text-foreground">
                          <span className="text-muted-foreground">Weekly Study:</span>
                          <span className="font-medium">{details.weeklyCommitment}</span>
                        </div>
                        <div className="flex justify-between items-start text-foreground pt-1 border-t border-border/40">
                          <span className="text-muted-foreground">Next Intake:</span>
                          <span className="font-bold text-primary text-right">
                            {cohort ? `${cohort.startDate} (${cohort.duration})` : 'First Monday next month'}
                          </span>
                        </div>
                          <div className="flex justify-between items-center text-[11px]">
                            <span className="text-muted-foreground">Status:</span>
                            <span className="font-bold text-teal">
                              Admissions Open
                            </span>
                          </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer Bar */}
        <div className="p-4 sm:p-5 border-t border-border bg-secondary/30 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs">
          <p className="text-muted-foreground text-center sm:text-left">
            Still unsure which pathway is right for you? Take our 60-second{' '}
            <button
              onClick={() => {
                setDrawerOpen(false);
                onNavigate('/');
                setTimeout(() => {
                  const el = document.getElementById('advisor');
                  if (el) el.scrollIntoView({ behavior: 'smooth' });
                }, 100);
              }}
              className="text-primary font-bold hover:underline cursor-pointer"
            >
              Interactive Career Pathway Quiz →
            </button>
          </p>

          <button
            onClick={() => setDrawerOpen(false)}
            className="px-5 py-2.5 rounded-full font-bold bg-primary text-primary-foreground hover:opacity-90 transition cursor-pointer self-stretch sm:self-auto text-center"
          >
            Done Comparing
          </button>
        </div>
      </div>
    </div>
  );
}

function ComparisonSectionHeader({
  icon,
  title,
  subtitle,
}: {
  icon: React.ReactNode;
  title: string;
  subtitle: string;
}) {
  return (
    <div className="pt-3 pb-1 border-b border-border/60">
      <div className="flex items-center gap-2">
        <span className="p-1.5 rounded-lg bg-card border border-border">{icon}</span>
        <h4 className="font-bold text-sm sm:text-base text-foreground">{title}</h4>
      </div>
      <p className="text-xs text-muted-foreground mt-0.5 ml-8">{subtitle}</p>
    </div>
  );
}
