import React, { useState, useEffect } from 'react';
import {
  Search,
  X,
  ArrowUpRight,
  Cloud,
  Cpu,
  Shield,
  Briefcase,
  FileText,
  Download,
  Award,
  Compass,
  Calendar,
  Scale,
  FileCheck,
  CheckCircle2,
  Clock,
  Sparkles,
} from 'lucide-react';
import { Container, Eyebrow } from '../components/Ui';
import { Reveal } from '../components/Brand';
import { COURSES, SUBJECTS, PROVIDERS, SubjectKey, ZiteCourse, searchCourses } from '../data/courses';
import { SyllabusModal } from '../components/SyllabusModal';
import { CourseOutlineRequestModal } from '../components/CourseOutlineRequestModal';
import { PathwayAdvisor } from '../components/PathwayAdvisor';
import { useComparison } from '../context/ComparisonContext';

interface ProgrammesPageProps {
  onNavigateCourse: (slug: string) => void;
  initialQuery?: string;
  initialSubject?: string;
  initialProvider?: string;
  initialCompare?: string;
}

export function ProgrammesPage({
  onNavigateCourse,
  initialQuery = '',
  initialSubject = '',
  initialProvider = '',
  initialCompare = '',
}: ProgrammesPageProps) {
  const [query, setQuery] = useState(initialQuery);
  const [selectedSubjects, setSelectedSubjects] = useState<SubjectKey[]>(
    initialSubject ? [initialSubject as SubjectKey] : []
  );
  const [selectedProviders, setSelectedProviders] = useState<string[]>(
    initialProvider ? [initialProvider] : []
  );
  const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'draft'>('all');
  const [visibleLimit, setVisibleLimit] = useState(30);

  // Modals state
  const [activeOutlineCourse, setActiveOutlineCourse] = useState<ZiteCourse | null>(null);
  const [activeSyllabusCourse, setActiveSyllabusCourse] = useState<ZiteCourse | null>(null);
  const [advisorModalOpen, setAdvisorModalOpen] = useState(false);

  const { setDrawerOpen, selectedSlugs, addCourse } = useComparison();

  useEffect(() => {
    setQuery(initialQuery || '');
    setSelectedSubjects(initialSubject ? [initialSubject as SubjectKey] : []);
    setSelectedProviders(initialProvider ? [initialProvider] : []);
    if (initialCompare) {
      const slugs = initialCompare.split(',').filter(Boolean);
      slugs.forEach((s) => addCourse(s));
      setDrawerOpen(true);
    }
  }, [initialQuery, initialSubject, initialProvider, initialCompare, addCourse, setDrawerOpen]);

  const toggleSubject = (subj: SubjectKey) => {
    setSelectedSubjects((prev) =>
      prev.includes(subj) ? prev.filter((s) => s !== subj) : [...prev, subj]
    );
  };

  const toggleProvider = (prov: string) => {
    setSelectedProviders((prev) =>
      prev.includes(prov) ? prev.filter((p) => p !== prov) : [...prev, prov]
    );
  };

  const clearFilters = () => {
    setQuery('');
    setSelectedSubjects([]);
    setSelectedProviders([]);
    setStatusFilter('all');
    setVisibleLimit(30);
  };

  // Reset limit when query or filters change
  useEffect(() => {
    setVisibleLimit(30);
  }, [query, selectedSubjects, selectedProviders, statusFilter]);

  // Filter pipeline
  const searched = searchCourses(query);
  const filtered = searched.filter((c) => {
    const matchesProvider = !selectedProviders.length || selectedProviders.includes(c.provider);
    const matchesSubject = !selectedSubjects.length || selectedSubjects.includes(c.subject);
    const matchesStatus =
      statusFilter === 'all' ||
      (statusFilter === 'approved' && c.publicationStatus === 'approved') ||
      (statusFilter === 'draft' && c.publicationStatus === 'draft');

    return matchesProvider && matchesSubject && matchesStatus;
  });

  const approvedCount = COURSES.filter((c) => c.publicationStatus === 'approved').length;
  const draftCount = COURSES.filter((c) => c.publicationStatus === 'draft').length;
  const hasFilters = Boolean(
    query.trim() || selectedSubjects.length || selectedProviders.length || statusFilter !== 'all'
  );

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section className="mesh border-b border-border/50">
        <Container className="pt-10 pb-10 grid gap-8 lg:grid-cols-12 items-center">
          <div className="lg:col-span-6 space-y-3">
            <div className="flex flex-wrap items-center gap-2">
              <Eyebrow>Catalogue · {approvedCount} Active Intakes · {draftCount} in Academic Review</Eyebrow>
            </div>

            <h1 className="text-3xl sm:text-5xl md:text-7xl font-bold leading-[1.02] mt-3 break-words">
              Find your next <span className="serif-accent text-teal">skill.</span>
            </h1>
            <p className="text-base sm:text-lg text-muted-foreground mt-4 max-w-lg leading-relaxed">
              Explore AWS, Google Cloud and Microsoft Azure training alongside AI, data, security, communication and online work programmes. Each programme includes an official PANIA-branded PDF course outline.
            </p>

            <div className="flex flex-wrap items-center gap-2.5 pt-2">
              <button
                onClick={() => setDrawerOpen(true)}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-bold border border-primary/30 bg-primary/10 hover:bg-primary/20 text-primary transition shadow-xs cursor-pointer"
              >
                <Scale className="h-3.5 w-3.5" />
                <span>Compare Tracks ({selectedSlugs.length})</span>
              </button>
              <a
                href="/#schedule"
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-bold bg-[#0B4035] text-[#D5E64D] hover:bg-[#072C24] transition shadow-xs border border-[#D5E64D]/20 cursor-pointer"
              >
                <Calendar className="h-3.5 w-3.5" />
                <span>Live Intake Schedule</span>
              </a>
              <button
                onClick={() => setAdvisorModalOpen(true)}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-bold bg-teal text-white hover:opacity-90 transition shadow-xs cursor-pointer"
              >
                <Compass className="h-3.5 w-3.5" />
                <span>Pathway Quiz</span>
              </button>
            </div>
          </div>

          {/* 4 Staggered Subject Cards in Hero Right */}
          <div className="lg:col-span-6 grid grid-cols-2 sm:grid-cols-4 gap-3">
            {(['cloud', 'ai', 'security', 'work'] as SubjectKey[]).map((subj, idx) => {
              const meta = SUBJECTS[subj];
              const isSelected = selectedSubjects.includes(subj);
              const subjectIcons = { cloud: Cloud, ai: Cpu, security: Shield, work: Briefcase };
              const Icon = subjectIcons[subj];

              return (
                <button
                  key={subj}
                  onClick={() => toggleSubject(subj)}
                  aria-pressed={isSelected}
                  className={`lift relative rounded-2xl overflow-hidden text-left aspect-[3/4] cursor-pointer transition-all ${
                    idx % 2 ? 'sm:mt-6' : ''
                  } ${isSelected ? 'ring-4 ring-accent' : ''}`}
                >
                  <img
                    src={meta.photo}
                    alt={meta.label}
                    className="absolute inset-0 w-full h-full object-cover"
                    loading="lazy"
                    decoding="async"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/20 to-transparent" />
                  <span className={`absolute top-2 left-2 h-8 w-8 rounded-lg grid place-items-center ${meta.bgSolid} text-white shadow-xs`}>
                    <Icon className="h-4 w-4" />
                  </span>
                  <span className="absolute bottom-2 left-2 right-2 text-white text-xs font-semibold leading-tight">
                    {meta.short}
                  </span>
                </button>
              );
            })}
          </div>
        </Container>
      </section>

      {/* Filter and Search Bar Section */}
      <Container className="py-8">
        <div className="space-y-6">
          {/* Search Input Box */}
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
            <input
              type="text"
              placeholder="Search by topic, skill, tool or role (e.g. AWS, AI, Cisco, Python, Azure, Linux)..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              className="w-full pl-12 pr-10 py-3.5 rounded-2xl bg-card border border-border text-foreground placeholder:text-muted-foreground text-sm focus:outline-hidden focus:ring-2 focus:ring-primary shadow-xs transition"
            />
            {query && (
              <button
                onClick={() => setQuery('')}
                className="absolute right-4 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground cursor-pointer"
                aria-label="Clear search"
              >
                <X className="h-4 w-4" />
              </button>
            )}
          </div>

          {/* Quick Filter Controls: Status Tabs, Category Pills, Providers */}
          <div className="flex flex-wrap items-center justify-between gap-4 pt-1">
            {/* Publication Status Selector */}
            <div className="flex items-center gap-1.5 p-1 rounded-2xl bg-secondary/60 border border-border">
              <button
                onClick={() => setStatusFilter('all')}
                className={`px-3 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer ${
                  statusFilter === 'all'
                    ? 'bg-primary text-primary-foreground shadow-2xs'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                All Programmes ({COURSES.length})
              </button>
              <button
                onClick={() => setStatusFilter('approved')}
                className={`px-3 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer flex items-center gap-1.5 ${
                  statusFilter === 'approved'
                    ? 'bg-[#0B4035] text-[#D5E64D] shadow-2xs'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                <CheckCircle2 className="h-3 w-3 text-emerald-500" />
                <span>Active Intakes ({approvedCount})</span>
              </button>
              <button
                onClick={() => setStatusFilter('draft')}
                className={`px-3 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer flex items-center gap-1.5 ${
                  statusFilter === 'draft'
                    ? 'bg-amber-600 text-white shadow-2xs'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                <Sparkles className="h-3 w-3" />
                <span>In Review ({draftCount})</span>
              </button>
            </div>

            {/* Provider Filters */}
            <div className="flex flex-wrap items-center gap-1.5">
              <span className="text-xs font-bold text-muted-foreground mr-1">Provider:</span>
              {PROVIDERS.map((prov) => {
                const isSelected = selectedProviders.includes(prov);
                return (
                  <button
                    key={prov}
                    onClick={() => toggleProvider(prov)}
                    aria-pressed={isSelected}
                    className={`px-3 py-1.5 rounded-xl text-xs font-semibold transition cursor-pointer border ${
                      isSelected
                        ? 'border-primary bg-primary text-primary-foreground shadow-2xs'
                        : 'border-border bg-card text-foreground hover:bg-secondary'
                    }`}
                  >
                    {prov}
                  </button>
                );
              })}
            </div>

            <div className="flex items-center gap-3">
              <span className="text-xs text-muted-foreground font-medium">
                Showing <strong className="text-foreground">{filtered.length}</strong> programmes
              </span>
              {hasFilters && (
                <button
                  onClick={clearFilters}
                  className="text-xs text-primary font-bold hover:underline cursor-pointer flex items-center gap-1"
                >
                  <X className="h-3 w-3" />
                  <span>Reset all</span>
                </button>
              )}
            </div>
          </div>
        </div>
      </Container>

      {/* Course Grid Results */}
      <Container className="pb-24">
        {filtered.length > 0 ? (
          <>
            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {filtered.slice(0, visibleLimit).map((course, idx) => (
                <CourseCard
                  key={course.code}
                  course={course}
                  i={idx}
                  onNavigateCourse={onNavigateCourse}
                  onRequestOutline={(c) => setActiveOutlineCourse(c)}
                />
              ))}
            </div>

            {filtered.length > visibleLimit && (
              <div className="mt-12 flex flex-col sm:flex-row items-center justify-center gap-3">
                <button
                  onClick={() => setVisibleLimit((prev) => prev + 30)}
                  className="px-6 py-3 rounded-2xl bg-primary text-primary-foreground font-bold text-xs sm:text-sm hover:opacity-95 transition shadow-sm cursor-pointer"
                >
                  Load More Programmes (+30)
                </button>
                <button
                  onClick={() => setVisibleLimit(filtered.length)}
                  className="px-5 py-3 rounded-2xl border border-border bg-card text-foreground font-semibold text-xs sm:text-sm hover:bg-secondary transition cursor-pointer"
                >
                  Show All {filtered.length} Programmes
                </button>
              </div>
            )}
          </>
        ) : (
          <div className="bg-card rounded-3xl p-12 text-center border border-border shadow-xs my-8 space-y-4 max-w-lg mx-auto">
            <h3 className="text-2xl font-bold">No programmes found</h3>
            <p className="text-sm text-muted-foreground leading-relaxed">
              We couldn&apos;t find any programmes matching your selected filters. Try broadening your keywords or clearing filters.
            </p>
            <button
              onClick={clearFilters}
              className="px-6 py-2.5 rounded-full bg-primary text-primary-foreground text-xs font-semibold hover:opacity-90 transition cursor-pointer"
            >
              Clear filters
            </button>
          </div>
        )}
      </Container>

      {/* Course-Specific Outline Request Modal (Gated PDF Download) */}
      {activeOutlineCourse && (
        <CourseOutlineRequestModal
          course={activeOutlineCourse}
          isOpen={Boolean(activeOutlineCourse)}
          onClose={() => setActiveOutlineCourse(null)}
          onNavigate={(path) => {
            setActiveOutlineCourse(null);
            const slug = path.split('/').pop() || '';
            if (path.startsWith('/programmes/')) {
              onNavigateCourse(slug);
            }
          }}
        />
      )}

      {/* General Syllabus Modal */}
      {activeSyllabusCourse && (
        <SyllabusModal
          course={activeSyllabusCourse}
          isOpen={Boolean(activeSyllabusCourse)}
          onClose={() => setActiveSyllabusCourse(null)}
          onNavigate={(path) => {
            setActiveSyllabusCourse(null);
            const slug = path.split('/').pop() || '';
            if (path.startsWith('/programmes/')) {
              onNavigateCourse(slug);
            }
          }}
        />
      )}



      {/* Pathway Advisor Quiz Modal */}
      {advisorModalOpen && (
        <PathwayAdvisor
          isModal
          onClose={() => setAdvisorModalOpen(false)}
          onNavigate={(path) => {
            setAdvisorModalOpen(false);
            const slug = path.split('/').pop() || '';
            if (path.startsWith('/programmes/')) {
              onNavigateCourse(slug);
            }
          }}
          onOpenSyllabus={(course) => {
            setAdvisorModalOpen(false);
            setActiveOutlineCourse(course);
          }}
        />
      )}
    </div>
  );
}

function CourseCard({
  course,
  i,
  onNavigateCourse,
  onRequestOutline,
}: {
  course: ZiteCourse;
  i: number;
  onNavigateCourse: (slug: string) => void;
  onRequestOutline: (course: ZiteCourse) => void;
}) {
  const meta = SUBJECTS[course.subject];
  const { toggleCourse, isInComparison } = useComparison();
  const compared = isInComparison(course.slug);
  const isApproved = course.publicationStatus === 'approved';

  return (
    <Reveal delay={Math.min(i, 6) * 0.04} className="h-full">
      <div
        className={`lift group h-full rounded-3xl overflow-hidden flex flex-col bg-card border shadow-xs transition-all ${
          compared ? 'border-primary ring-2 ring-primary/30' : 'border-border hover:border-primary/30'
        }`}
      >
        {/* Card Header Image with Click Navigation */}
        <div
          onClick={() => onNavigateCourse(course.slug)}
          className="relative overflow-hidden h-48 shrink-0 cursor-pointer"
        >
          <img
            src={course.image || meta.photo}
            alt={course.title}
            className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
            loading="lazy"
            decoding="async"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black/65 via-black/15 to-transparent" />

          {/* Provider Badge */}
          <span className={`absolute top-3 left-3 text-xs font-semibold px-2.5 py-1 rounded-full text-white ${meta.bgSolid} shadow-xs`}>
            {course.provider}
          </span>

          {/* Status Badge */}
          {!isApproved && (
            <span className="absolute bottom-3 left-3 text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-400 text-amber-950 shadow-xs flex items-center gap-1">
              <Clock className="w-2.5 h-2.5" />
              <span>In Review</span>
            </span>
          )}

          {/* Compare Badge / Button on Image */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              toggleCourse(course.slug);
            }}
            className={`absolute top-3 right-3 px-2.5 py-1 rounded-full text-xs font-bold transition-all shadow-xs cursor-pointer flex items-center gap-1.5 backdrop-blur-md ${
              compared
                ? 'bg-[#D5E64D] text-[#072C24] ring-2 ring-white/50'
                : 'bg-black/50 hover:bg-black/80 text-white'
            }`}
            title={compared ? 'Remove from comparison' : 'Compare track side-by-side'}
          >
            <Scale className="w-3 h-3" />
            <span>{compared ? 'Comparing' : 'Compare'}</span>
          </button>
        </div>

        {/* Card Content */}
        <div className="p-6 flex flex-col justify-between flex-1 space-y-4">
          <div
            onClick={() => onNavigateCourse(course.slug)}
            className="space-y-2 cursor-pointer"
          >
            <div className="flex items-center justify-between">
              <p className="text-xs font-semibold text-muted-foreground">
                {meta.label} · Fully online
              </p>
              <span className="text-[11px] font-mono font-bold text-primary">
                {course.code}
              </span>
            </div>

            <h3 className="text-xl font-bold leading-tight group-hover:text-primary transition-colors">
              {course.title}
            </h3>

            <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">
              {course.who}
            </p>
          </div>

          <div className="pt-3 border-t border-border flex items-center justify-between text-xs font-bold text-foreground">
            <button
              onClick={() => onRequestOutline(course)}
              className="inline-flex items-center gap-1.5 text-primary hover:underline transition cursor-pointer"
              title="Request Official Outline PDF"
            >
              <Download className="h-3.5 w-3.5" />
              <span>Outline (PDF)</span>
            </button>

            <button
              onClick={() => toggleCourse(course.slug)}
              className={`inline-flex items-center gap-1 transition cursor-pointer ${
                compared ? 'text-primary font-bold' : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              <Scale className="h-3.5 w-3.5" />
              <span>{compared ? 'In Comparison' : 'Compare'}</span>
            </button>

            <a
              href={`#/programmes/${course.slug}`}
              onClick={(e) => {
                if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                  e.preventDefault();
                  onNavigateCourse(course.slug);
                }
              }}
              className="inline-flex items-center gap-1 group-hover:underline text-primary cursor-pointer min-h-[36px]"
            >
              <span>View details</span>
              <ArrowUpRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" aria-hidden="true" />
            </a>
          </div>
        </div>
      </div>
    </Reveal>
  );
}
