import React, { useState, useEffect, useRef } from 'react';
import {
  X,
  Download,
  CheckCircle2,
  AlertCircle,
  FileText,
  Building,
  User,
  Mail,
  Phone,
  Clock,
  ShieldCheck,
  Send,
  Loader2,
  ExternalLink,
  MessageCircle,
  Sparkles,
  Lock,
  Eye,
} from 'lucide-react';
import { ZiteCourse } from '../data/courses';

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

interface SubmissionResponse {
  success: boolean;
  enquiryRef?: string;
  isDraft?: boolean;
  publicationStatus?: 'approved' | 'draft';
  emailStatus?: string;
  downloadToken?: string;
  expiresAt?: number;
  courseTitle?: string;
  courseSlug?: string;
  downloadUrl?: string;
  filename?: string;
  firstName?: string;
  message?: string;
  error?: string;
}

export function CourseOutlineRequestModal({
  course,
  isOpen,
  onClose,
  onNavigate,
}: CourseOutlineRequestModalProps) {
  // Form state
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [organisation, setOrganisation] = useState('');
  const [audienceType, setAudienceType] = useState<'individual' | 'team'>('individual');
  const [contactMethod, setContactMethod] = useState<'email' | 'whatsapp' | 'phone'>('email');
  const [timeframe, setTimeframe] = useState('Immediate intake');
  const [message, setMessage] = useState('');
  const [honeypot, setHoneypot] = useState('');

  // UI state
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<SubmissionResponse | null>(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const [downloadStarted, setDownloadStarted] = useState(false);
  const [downloadBlobUrl, setDownloadBlobUrl] = useState<string | null>(null);
  const [downloadError, setDownloadError] = useState<string | null>(null);

  // Focus trap ref
  const modalContainerRef = useRef<HTMLDivElement>(null);
  const previousActiveElement = useRef<HTMLElement | null>(null);

  // Reset or initialize on open
  useEffect(() => {
    if (isOpen) {
      previousActiveElement.current = document.activeElement as HTMLElement;
      setError(null);
      setResult(null);
      setDownloadStarted(false);
      document.body.style.overflow = 'hidden';

      if (modalContainerRef.current) {
        modalContainerRef.current.focus();
      }
    } else {
      document.body.style.overflow = '';
      if (previousActiveElement.current && typeof previousActiveElement.current.focus === 'function') {
        previousActiveElement.current.focus();
      }
    }

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

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const isApproved = course.publicationStatus !== 'draft';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    // Client-side validations
    if (!fullName.trim() || fullName.trim().length < 2) {
      setError('Please provide your full name.');
      return;
    }

    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email.trim() || !emailPattern.test(email.trim())) {
      setError('Please provide a valid email address.');
      return;
    }

    if ((contactMethod === 'whatsapp' || contactMethod === 'phone') && (!phone.trim() || phone.trim().length < 7)) {
      setError('Please provide your phone / WhatsApp number for your chosen contact preference.');
      return;
    }

    if (audienceType === 'team' && !organisation.trim()) {
      setError('Please enter your company / organisation name for team training enquiries.');
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await fetch('/api/enquire-outline', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName: fullName.trim(),
          email: email.trim(),
          phone: phone.trim() || undefined,
          organisation: organisation.trim() || undefined,
          audienceType,
          contactMethod,
          timeframe,
          message: message.trim() || undefined,
          courseSlug: course.slug,
          sourcePage: `/programmes/${course.slug}`,
          honeypot: honeypot.trim() || undefined,
        }),
      });

      const data: SubmissionResponse = await response.json();

      if (!response.ok || !data.success) {
        setError(data.error || 'Unable to process your request. Please try again.');
        setIsSubmitting(false);
        return;
      }

      setResult(data);
      setIsSubmitting(false);
    } catch (err: any) {
      console.error('Outline enquiry submission error:', err);
      setError('A network error occurred. Please check your connection and try again.');
      setIsSubmitting(false);
    }
  };

  const handleDownload = async () => {
    if (!result?.downloadUrl) return;
    setIsDownloading(true);
    setDownloadError(null);
    try {
      const res = await fetch(result.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);

      // Trigger automatic save
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = result.filename || `PANIA_${course.slug}_Course_Outline.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      setDownloadStarted(true);
    } catch (err: any) {
      console.error('Outline download error:', err);
      setDownloadError(err.message || 'Unable to download the PDF. Please try opening it online or contact us via WhatsApp.');
    } finally {
      setIsDownloading(false);
    }
  };

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

  const whatsappInquiryUrl = `https://wa.me/254101936893?text=${encodeURIComponent(
    `Hello PANIA admissions desk, I submitted enquiry ${result?.enquiryRef || ''} for ${course.title} and would like to speak with an advisor.`
  )}`;

  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="outline-modal-title"
    >
      <div
        ref={modalContainerRef}
        tabIndex={-1}
        className="bg-card w-full max-w-2xl rounded-3xl border border-border shadow-2xl overflow-hidden flex flex-col max-h-[92vh] outline-hidden animate-in fade-in zoom-in-95 duration-200"
      >
        {/* Header */}
        <div className="p-6 border-b border-border bg-[#0B4035] text-white flex items-start justify-between gap-4">
          <div className="space-y-1.5">
            <div className="flex flex-wrap items-center gap-2">
              <span className="inline-flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider bg-[#D5E64D] text-[#072C24] px-2.5 py-0.5 rounded-full">
                <FileText className="h-3.5 w-3.5" />
                <span>Course Outline & Curriculum</span>
              </span>
              <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-white/15 text-white">
                Ref: {course.code}
              </span>
              {isApproved ? (
                <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-emerald-400/20 text-emerald-300 flex items-center gap-1">
                  <ShieldCheck className="h-3 w-3" />
                  <span>Approved Syllabus</span>
                </span>
              ) : (
                <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full bg-amber-400/20 text-amber-200 flex items-center gap-1">
                  <Sparkles className="h-3 w-3" />
                  <span>Candidate Draft</span>
                </span>
              )}
            </div>

            <h2 id="outline-modal-title" className="text-xl sm:text-2xl font-bold tracking-tight text-white">
              {course.title}
            </h2>
            <p className="text-xs text-white/80">
              Provider: <span className="font-semibold text-white">{course.provider}</span> · 100% Online Cohorts
            </p>
          </div>

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

        {/* Modal Body */}
        <div className="p-6 overflow-y-auto space-y-6 text-sm">
          {result ? (
            // Success Screen
            <div className="space-y-6 py-2">
              <div className="rounded-2xl p-6 bg-emerald-500/10 border border-emerald-500/20 text-foreground space-y-4">
                <div className="flex items-start gap-3">
                  <div className="h-10 w-10 rounded-full bg-emerald-600 text-white flex items-center justify-center shrink-0">
                    <CheckCircle2 className="h-6 w-6" />
                  </div>
                  <div>
                    <h3 className="text-lg font-bold text-foreground">
                      {isApproved ? 'Outline Ready for Download' : 'Enquiry Registered'}
                    </h3>
                    <p className="text-xs text-muted-foreground mt-0.5 font-mono">
                      Enquiry Reference: <span className="font-bold text-primary">{result.enquiryRef}</span>
                    </p>
                  </div>
                </div>

                <p className="text-sm text-foreground/90 leading-relaxed">
                  {result.message}
                </p>

                {result.downloadUrl && (
                  <div className="pt-2 space-y-2.5">
                    <button
                      onClick={handleDownload}
                      disabled={isDownloading}
                      className="w-full inline-flex items-center justify-center gap-2.5 px-6 py-3.5 rounded-2xl font-bold text-sm bg-[#0B4035] text-[#D5E64D] hover:bg-[#072C24] transition shadow-md cursor-pointer disabled:opacity-75"
                    >
                      {isDownloading ? (
                        <>
                          <Loader2 className="h-5 w-5 animate-spin" />
                          <span>Generating & Preparing PDF…</span>
                        </>
                      ) : (
                        <>
                          <Download className="h-5 w-5" />
                          <span>Download {course.title} Outline (PDF)</span>
                        </>
                      )}
                    </button>

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

                    {downloadStarted && (
                      <p className="text-[11px] text-emerald-700 text-center mt-2 flex items-center justify-center gap-1 font-medium">
                        <CheckCircle2 className="h-3.5 w-3.5" />
                        <span>Download started. Check your device's downloads folder.</span>
                      </p>
                    )}

                    {downloadError && (
                      <p className="text-[11px] text-destructive text-center mt-2 flex items-center justify-center gap-1 font-medium">
                        <AlertCircle className="h-3.5 w-3.5" />
                        <span>{downloadError}</span>
                      </p>
                    )}
                  </div>
                )}
              </div>

              {/* Action Buttons */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <a
                  href={whatsappInquiryUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center justify-center gap-2 px-4 py-3 rounded-xl border border-border bg-card hover:bg-secondary text-foreground text-xs font-bold transition shadow-2xs cursor-pointer"
                >
                  <MessageCircle className="h-4 w-4 text-[#207A78]" />
                  <span>Follow Up on WhatsApp</span>
                </a>

                <button
                  onClick={() => {
                    onClose();
                    if (onNavigate) {
                      onNavigate(`/contact?mode=learner&course=${course.slug}`);
                    }
                  }}
                  className="inline-flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-[#D5E64D] text-[#072C24] hover:brightness-95 text-xs font-bold transition shadow-2xs cursor-pointer"
                >
                  <span>Apply for Next Cohort</span>
                </button>
              </div>

              <div className="text-center pt-2">
                <button
                  onClick={() => {
                    setResult(null);
                    setDownloadStarted(false);
                  }}
                  className="text-xs text-muted-foreground hover:text-foreground underline cursor-pointer"
                >
                  Submit another enquiry or change details
                </button>
              </div>
            </div>
          ) : (
            // Enquiry Form
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="bg-secondary/40 rounded-2xl p-4 border border-border/60">
                <p className="text-xs text-foreground/90 leading-relaxed">
                  Enter your details below to unlock the complete PANIA-branded PDF course outline, including week-by-week module breakdowns, practical lab exercises, and intake schedules.
                </p>
              </div>

              {error && (
                <div className="p-3.5 rounded-xl bg-destructive/10 border border-destructive/20 text-destructive text-xs font-medium flex items-start gap-2.5">
                  <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
                  <span>{error}</span>
                </div>
              )}

              {/* Audience Selector: Individual vs Team */}
              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-muted-foreground mb-1.5">
                  I am inquiring for:
                </label>
                <div className="grid grid-cols-2 gap-3">
                  <button
                    type="button"
                    onClick={() => setAudienceType('individual')}
                    className={`p-3 rounded-xl border text-xs font-bold flex items-center justify-center gap-2 transition cursor-pointer ${
                      audienceType === 'individual'
                        ? 'border-primary bg-primary/10 text-primary ring-1 ring-primary'
                        : 'border-border bg-background text-muted-foreground hover:text-foreground'
                    }`}
                  >
                    <User className="h-4 w-4" />
                    <span>My Own Learning</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setAudienceType('team')}
                    className={`p-3 rounded-xl border text-xs font-bold flex items-center justify-center gap-2 transition cursor-pointer ${
                      audienceType === 'team'
                        ? 'border-primary bg-primary/10 text-primary ring-1 ring-primary'
                        : 'border-border bg-background text-muted-foreground hover:text-foreground'
                    }`}
                  >
                    <Building className="h-4 w-4" />
                    <span>My Team / Corporate</span>
                  </button>
                </div>
              </div>

              {/* Name & Email Fields */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label htmlFor="outline-fullname" className="block text-xs font-bold text-foreground mb-1">
                    Full Name <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <input
                      id="outline-fullname"
                      type="text"
                      required
                      placeholder="e.g. Grace Mwangi"
                      value={fullName}
                      onChange={(e) => setFullName(e.target.value)}
                      className="w-full pl-9 pr-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="outline-email" className="block text-xs font-bold text-foreground mb-1">
                    Email Address <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <input
                      id="outline-email"
                      type="email"
                      required
                      placeholder="e.g. grace@example.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="w-full pl-9 pr-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>
              </div>

              {/* Phone & Organisation */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label htmlFor="outline-phone" className="block text-xs font-bold text-foreground mb-1">
                    Phone / WhatsApp {contactMethod !== 'email' && <span className="text-destructive">*</span>}
                  </label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <input
                      id="outline-phone"
                      type="tel"
                      placeholder="e.g. +254 712 345 678"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      className="w-full pl-9 pr-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="outline-org" className="block text-xs font-bold text-foreground mb-1">
                    Organisation {audienceType === 'team' && <span className="text-destructive">*</span>}
                  </label>
                  <div className="relative">
                    <Building className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <input
                      id="outline-org"
                      type="text"
                      placeholder={audienceType === 'team' ? 'Company name (required)' : 'Company / College (optional)'}
                      value={organisation}
                      onChange={(e) => setOrganisation(e.target.value)}
                      className="w-full pl-9 pr-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>
              </div>

              {/* Contact Method & Timeframe */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold text-foreground mb-1">
                    Preferred Contact Channel
                  </label>
                  <select
                    value={contactMethod}
                    onChange={(e) => setContactMethod(e.target.value as any)}
                    className="w-full px-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                  >
                    <option value="email">Email</option>
                    <option value="whatsapp">WhatsApp</option>
                    <option value="phone">Phone Call</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-foreground mb-1">
                    Learning Timeframe
                  </label>
                  <select
                    value={timeframe}
                    onChange={(e) => setTimeframe(e.target.value)}
                    className="w-full px-3 py-2.5 rounded-xl border border-border bg-background text-xs text-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
                  >
                    <option value="Immediate intake">Immediate Cohort Intake</option>
                    <option value="Next 1-3 months">Next 1–3 Months</option>
                    <option value="Corporate / Team planning">Corporate Team Planning</option>
                    <option value="Just researching">Just Researching Curricula</option>
                  </select>
                </div>
              </div>

              {/* Optional Message */}
              <div>
                <label htmlFor="outline-message" className="block text-xs font-bold text-foreground mb-1">
                  Specific Questions or Learning Objectives (Optional)
                </label>
                <textarea
                  id="outline-message"
                  rows={2}
                  placeholder="Tell our advisors if you have specific goals, laptop specs questions, or employer sponsorship needs..."
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  className="w-full p-3 rounded-xl border border-border bg-background text-xs text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary resize-none"
                />
              </div>

              {/* Honeypot field for bot spam prevention */}
              <div style={{ display: 'none' }} aria-hidden="true">
                <input
                  type="text"
                  name="honeypot"
                  tabIndex={-1}
                  value={honeypot}
                  onChange={(e) => setHoneypot(e.target.value)}
                  autoComplete="off"
                />
              </div>

              {/* Privacy Notice */}
              <div className="flex items-start gap-2 pt-1 text-[11px] text-muted-foreground leading-normal">
                <ShieldCheck className="h-4 w-4 text-primary shrink-0 mt-0.5" />
                <span>
                  Your details are shared only with PANIA admissions advisors to provide course guidance and intake details. We never share or sell your information.
                </span>
              </div>

              {/* Submit CTA */}
              <div className="pt-2">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl font-bold text-xs sm:text-sm bg-[#0B4035] text-[#D5E64D] hover:bg-[#072C24] transition shadow-md disabled:opacity-50 cursor-pointer"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span>Sending Enquiry & Verifying...</span>
                    </>
                  ) : (
                    <>
                      <Send className="h-4 w-4" />
                      <span>Send Enquiry & Unlock Outline</span>
                    </>
                  )}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
