import React, { useState } from 'react';
import {
  X,
  Download,
  Printer,
  Calendar,
  CheckCircle2,
  Clock,
  BookOpen,
  Send,
  MessageCircle,
  FileText,
  Award,
  Loader2,
  ShieldCheck,
  AlertCircle,
  Eye,
} from 'lucide-react';
import { ZiteCourse, COURSES } from '../data/courses';

interface SyllabusModalProps {
  course?: ZiteCourse;
  isOpen: boolean;
  onClose: () => void;
  onNavigate?: (path: string) => void;
}

export function SyllabusModal({
  course: initialCourse,
  isOpen,
  onClose,
  onNavigate,
}: SyllabusModalProps) {
  const [selectedCourseSlug, setSelectedCourseSlug] = useState<string>(
    initialCourse?.slug || COURSES[0].slug
  );
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
  const [downloadFilename, setDownloadFilename] = useState<string>('');
  const [enquiryRef, setEnquiryRef] = useState<string | null>(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const [downloadBlobUrl, setDownloadBlobUrl] = useState<string | null>(null);
  const [downloadError, setDownloadError] = useState<string | null>(null);

  const previousActiveElement = React.useRef<HTMLElement | null>(null);
  const modalContainerRef = React.useRef<HTMLDivElement>(null);

  // Sync state if initialCourse changes
  React.useEffect(() => {
    if (initialCourse?.slug) {
      setSelectedCourseSlug(initialCourse.slug);
      setDownloadUrl(null);
      setEnquiryRef(null);
      setErrorMessage(null);
    }
  }, [initialCourse?.slug]);

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

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

    if (modalContainerRef.current) {
      modalContainerRef.current.focus();
    }

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

    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();
      }
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const currentCourse =
    COURSES.find((c) => c.slug === selectedCourseSlug) || initialCourse || COURSES[0];

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

  const handleEnquirySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);

    if (!fullName.trim() || fullName.trim().length < 2) {
      setErrorMessage('Please provide your full name.');
      return;
    }

    if (!email.trim() || !email.includes('@')) {
      setErrorMessage('Please enter a valid email address.');
      return;
    }

    setIsSubmitting(true);

    try {
      const res = await fetch('/api/enquire-outline', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName: fullName.trim(),
          email: email.trim(),
          courseSlug: currentCourse.slug,
          sourcePage: `/programmes/${currentCourse.slug}`,
          contactMethod: 'email',
          timeframe: 'Immediate intake',
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.success) {
        setErrorMessage(data.error || 'Failed to submit enquiry. Please try again.');
        setIsSubmitting(false);
        return;
      }

      setEnquiryRef(data.enquiryRef);
      if (data.downloadUrl) {
        setDownloadUrl(data.downloadUrl);
        setDownloadFilename(data.filename || `${currentCourse.slug}_Outline.pdf`);
      }
      setIsSubmitting(false);
    } catch (err: any) {
      console.error('Error submitting enquiry:', err);
      setErrorMessage('Network error occurred. Please check your connection and retry.');
      setIsSubmitting(false);
    }
  };

  const handleDownload = async () => {
    if (!downloadUrl) return;
    setIsDownloading(true);
    setDownloadError(null);
    try {
      const res = await fetch(downloadUrl);
      if (!res.ok) {
        throw new Error(`Server returned HTTP ${res.status}. Could not fetch outline PDF.`);
      }
      const blob = await res.blob();
      const pdfBlob = new Blob([blob], { type: 'application/pdf' });
      const blobUrl = window.URL.createObjectURL(pdfBlob);
      setDownloadBlobUrl(blobUrl);

      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = downloadFilename || `PANIA_${currentCourse.slug}_Course_Outline.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (err: any) {
      console.error('Syllabus download error:', err);
      setDownloadError(err.message || 'Unable to download the PDF. Please try opening it online.');
    } finally {
      setIsDownloading(false);
    }
  };

  const handleOpenPdfOnline = () => {
    if (downloadBlobUrl) {
      window.open(downloadBlobUrl, '_blank');
    } else if (downloadUrl) {
      window.open(`${downloadUrl}&view=1`, '_blank');
    }
  };

  const whatsappSyllabusUrl = `https://wa.me/254101936893?text=${encodeURIComponent(
    `Hello PANIA, please send me the complete PDF syllabus and intake schedule for ${currentCourse.title}.`
  )}`;

  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"
      aria-labelledby="syllabus-modal-title"
    >
      <div
        ref={modalContainerRef}
        tabIndex={-1}
        className="bg-card w-full max-w-3xl rounded-3xl border border-border shadow-2xl overflow-hidden flex flex-col max-h-[90vh] outline-hidden"
      >
        {/* Header */}
        <div className="p-6 border-b border-border bg-secondary/40 flex items-start justify-between gap-4">
          <div>
            <div className="flex items-center gap-2">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-primary">
                <FileText className="h-4 w-4" />
                <span>Official Course Syllabus & Curriculum</span>
              </span>
              <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-primary/10 text-primary">
                Doc Ref: {currentCourse.code}
              </span>
            </div>
            <h2 id="syllabus-modal-title" className="text-xl sm:text-2xl font-bold mt-1 text-foreground">
              {currentCourse.title}
            </h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              Provider: <span className="font-semibold text-foreground">{currentCourse.provider}</span> · 100% Online Delivery
            </p>
          </div>

          <button
            onClick={onClose}
            aria-label="Close modal"
            className="p-2 rounded-full hover:bg-secondary text-muted-foreground hover:text-foreground transition cursor-pointer"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Course Selector Dropdown (Allows browsing other syllabi) */}
        <div className="px-6 py-3 bg-card border-b border-border/60 flex items-center gap-3">
          <label htmlFor="syllabus-course-select" className="text-xs font-bold text-muted-foreground whitespace-nowrap">
            Switch Programme:
          </label>
          <select
            id="syllabus-course-select"
            value={selectedCourseSlug}
            onChange={(e) => {
              setSelectedCourseSlug(e.target.value);
              setDownloadUrl(null);
              setEnquiryRef(null);
            }}
            className="w-full text-xs font-medium rounded-xl border border-border bg-background px-3 py-2 text-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
          >
            {COURSES.map((c) => (
              <option key={c.slug} value={c.slug}>
                {c.title} ({c.provider}) {c.publicationStatus === 'draft' ? '[Candidate Draft]' : ''}
              </option>
            ))}
          </select>
        </div>

        {/* Scrollable Content Body */}
        <div className="p-6 overflow-y-auto space-y-6 text-sm print:overflow-visible">
          {/* Target Audience & Overview */}
          <div className="bg-secondary/40 rounded-2xl p-4 border border-border/50">
            <h3 className="font-bold text-xs uppercase text-muted-foreground tracking-wider">
              Target Profile & Prerequisites
            </h3>
            <p className="text-foreground mt-1 text-xs sm:text-sm leading-relaxed">
              {currentCourse.who}
            </p>
          </div>

          {/* Module-by-Module Learning Outcomes */}
          <div>
            <h3 className="font-bold text-sm text-foreground flex items-center gap-2">
              <BookOpen className="h-4 w-4 text-primary" />
              <span>Curriculum Learning Modules</span>
            </h3>
            <div className="mt-3 space-y-2.5">
              {currentCourse.outcomes.map((outcome, idx) => (
                <div
                  key={idx}
                  className="flex items-start gap-3 p-3 rounded-xl bg-background border border-border/70"
                >
                  <span className="h-6 w-6 rounded-lg bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0 mt-0.5">
                    M{idx + 1}
                  </span>
                  <div>
                    <p className="font-bold text-xs text-foreground">
                      Module {idx + 1}: {outcome}
                    </p>
                    <p className="text-[11px] text-muted-foreground mt-0.5">
                      Hands-on walkthroughs, guided exercises and competency checks.
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Capstone & Practical Lab */}
          <div className="rounded-2xl p-4 bg-teal/10 border border-teal/20 text-foreground">
            <div className="flex items-center gap-2">
              <Award className="h-4 w-4 text-teal" />
              <h3 className="font-bold text-xs text-teal uppercase tracking-wider">
                Applied Capstone & Practical Work
              </h3>
            </div>
            <p className="mt-2 text-xs sm:text-sm leading-relaxed font-medium">
              {currentCourse.practical}
            </p>
          </div>

          {/* Cohort & Schedule Strip */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
            <div className="p-3 rounded-xl bg-secondary/50 border border-border">
              <div className="flex items-center gap-1.5 font-bold text-foreground">
                <Calendar className="h-3.5 w-3.5 text-accent" />
                <span>Next Intake</span>
              </div>
              <p className="text-muted-foreground mt-1">First Monday of upcoming month</p>
            </div>

            <div className="p-3 rounded-xl bg-secondary/50 border border-border">
              <div className="flex items-center gap-1.5 font-bold text-foreground">
                <Clock className="h-3.5 w-3.5 text-ocean" />
                <span>Format & Schedule</span>
              </div>
              <p className="text-muted-foreground mt-1">Evening & Weekend Live Sessions</p>
            </div>

            <div className="p-3 rounded-xl bg-secondary/50 border border-border">
              <div className="flex items-center gap-1.5 font-bold text-foreground">
                <CheckCircle2 className="h-3.5 w-3.5 text-teal" />
                <span>Certification Support</span>
              </div>
              <p className="text-muted-foreground mt-1">Mock tests & voucher guidance</p>
            </div>
          </div>

          {/* Enquiry-Gated PDF Download Form */}
          <div className="bg-card rounded-2xl p-5 border border-border shadow-xs space-y-3">
            <h4 className="font-bold text-xs sm:text-sm text-foreground flex items-center gap-2">
              <Download className="h-4 w-4 text-primary" />
              <span>Unlock Branded PDF Course Outline</span>
            </h4>
            <p className="text-xs text-muted-foreground">
              Provide your name and email to immediately download the comprehensive A4 outline with module objectives, portfolio deliverables, and tuition breakdown.
            </p>

            {errorMessage && (
              <div className="p-3 rounded-xl bg-destructive/10 text-destructive text-xs font-semibold flex items-center gap-2">
                <AlertCircle className="h-4 w-4 shrink-0" />
                <span>{errorMessage}</span>
              </div>
            )}

            {enquiryRef ? (
              <div className="p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-foreground space-y-3">
                <div className="flex items-center gap-2 text-emerald-800 text-xs font-bold">
                  <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                  <span>Enquiry registered! Reference ID: {enquiryRef}</span>
                </div>
                {downloadUrl ? (
                  <div className="space-y-2">
                    <button
                      onClick={handleDownload}
                      disabled={isDownloading}
                      className="w-full inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-[#0B4035] text-[#D5E64D] hover:bg-[#072C24] font-bold text-xs sm:text-sm transition cursor-pointer disabled:opacity-75"
                    >
                      {isDownloading ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span>Preparing Outline PDF…</span>
                        </>
                      ) : (
                        <>
                          <Download className="h-4 w-4" />
                          <span>Download Official PDF Outline</span>
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleOpenPdfOnline}
                      type="button"
                      className="w-full inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-border bg-card hover:bg-secondary text-foreground text-xs font-semibold transition cursor-pointer"
                    >
                      <Eye className="h-3.5 w-3.5 text-teal" />
                      <span>Open & Read PDF Online in Browser</span>
                    </button>

                    {downloadError && (
                      <p className="text-[11px] text-destructive text-center mt-1 flex items-center justify-center gap-1 font-medium">
                        <AlertCircle className="h-3 w-3" />
                        <span>{downloadError}</span>
                      </p>
                    )}
                  </div>
                ) : (
                  <p className="text-xs text-muted-foreground">
                    This syllabus is currently in candidate review. Our admissions team has logged your enquiry and will contact you directly with approved intake materials.
                  </p>
                )}
              </div>
            ) : (
              <form onSubmit={handleEnquirySubmit} className="space-y-3 pt-1">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  <input
                    type="text"
                    required
                    placeholder="Full name (e.g. Grace Mwangi)"
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    className="w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                  />
                  <input
                    type="email"
                    required
                    placeholder="Email address (e.g. grace@example.com)"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                  />
                </div>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full rounded-xl px-4 py-3 bg-[#0B4035] text-[#D5E64D] hover:bg-[#072C24] text-xs font-bold flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="h-3.5 w-3.5 animate-spin" />
                      <span>Sending Enquiry & Generating PDF Link...</span>
                    </>
                  ) : (
                    <>
                      <Send className="h-3.5 w-3.5" />
                      <span>Send Enquiry & Unlock Outline</span>
                    </>
                  )}
                </button>
                <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
                  <ShieldCheck className="h-3.5 w-3.5 text-primary" />
                  <span>Enquiries are handled directly by PANIA Admissions Desk. No spam.</span>
                </div>
              </form>
            )}
          </div>
        </div>

        {/* Footer Actions */}
        <div className="p-4 border-t border-border bg-secondary/30 flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <button
              onClick={handlePrint}
              className="inline-flex items-center gap-1.5 text-xs font-semibold px-3.5 py-2 rounded-xl border border-border bg-card hover:bg-secondary transition cursor-pointer text-foreground"
            >
              <Printer className="h-3.5 w-3.5" />
              <span>Print Page</span>
            </button>

            <a
              href={whatsappSyllabusUrl}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 text-xs font-semibold px-3.5 py-2 rounded-xl bg-teal text-white hover:opacity-90 transition cursor-pointer"
            >
              <MessageCircle className="h-3.5 w-3.5" />
              <span>Ask on WhatsApp</span>
            </a>
          </div>

          <button
            onClick={() => {
              onClose();
              if (onNavigate) {
                onNavigate(`/contact?mode=learner&course=${currentCourse.slug}`);
              }
            }}
            className="inline-flex items-center gap-1.5 text-xs font-bold px-4 py-2 rounded-xl bg-accent text-accent-foreground hover:brightness-95 transition cursor-pointer"
          >
            <span>Enrol in Programme</span>
          </button>
        </div>
      </div>
    </div>
  );
}
