import React, { useState, useEffect, useRef } from 'react';
import {
  MessageCircle,
  X,
  Send,
  Sparkles,
  Laptop,
  Calendar,
  CreditCard,
  Briefcase,
  UserCheck,
  Video,
  Clock,
  ShieldCheck,
  ArrowUpRight,
} from 'lucide-react';
import { BRAND } from './Brand';
import { useComparison } from '../context/ComparisonContext';

interface QuickPrompt {
  id: string;
  icon: React.ElementType;
  label: string;
  message: string;
  badge?: string;
}

const QUICK_PROMPTS: QuickPrompt[] = [
  {
    id: 'fees',
    icon: CreditCard,
    label: 'Ask about fees & installments',
    message: 'Hello PANIA Admissions, could you please explain the course fees, early bird discount, and 2-part milestone installment plans?',
    badge: 'Popular',
  },
  {
    id: 'laptop',
    icon: Laptop,
    label: 'Check my laptop & hardware specs',
    message: 'Hello PANIA, I want to confirm if my current laptop and computer specifications will work for the online sandboxed cloud labs.',
    badge: 'Hardware',
  },
  {
    id: 'zoom',
    icon: Video,
    label: 'What if I miss a live Zoom class?',
    message: 'Hello PANIA, could you clarify how class recordings, replays, and WhatsApp group support work if I miss a live Zoom session?',
    badge: 'Recordings',
  },
  {
    id: 'career',
    icon: Briefcase,
    label: 'CV reviews & job interview support',
    message: 'Hello PANIA, can you tell me more about the post-graduation career support, CV revamping, and employer linkages you offer?',
    badge: 'Careers',
  },
  {
    id: 'schedule',
    icon: Calendar,
    label: 'Next intake & cohort dates',
    message: 'Hello PANIA, what are the upcoming cohort intake dates and weekly class schedules for your programmes?',
  },
  {
    id: 'advisor',
    icon: UserCheck,
    label: 'Speak with an admissions advisor',
    message: 'Hello PANIA, I would like to schedule a 1-on-1 consultation with an academic advisor to discuss the best learning track for my career goal.',
  },
];

export function QuickWhatsAppDesk() {
  const [isOpen, setIsOpen] = useState(false);
  const [customMessage, setCustomMessage] = useState('');
  const [hasInteracted, setHasInteracted] = useState(false);
  const { selectedSlugs } = useComparison();
  const hasComparedCourses = selectedSlugs.length > 0;

  const popoverRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Close on outside click
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        isOpen &&
        popoverRef.current &&
        !popoverRef.current.contains(event.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen]);

  const handleSelectPrompt = (message: string) => {
    setCustomMessage(message);
    setHasInteracted(true);
  };

  const handleSendToWhatsApp = (text?: string) => {
    const finalMsg = (text || customMessage || 'Hello PANIA Admissions, I have an enquiry about your programmes.').trim();
    const url = `https://wa.me/254101936893?text=${encodeURIComponent(finalMsg)}`;
    window.open(url, '_blank', 'noopener,noreferrer');
    setIsOpen(false);
  };

  return (
    <>
      {/* Floating Action Trigger Button */}
      <div
        className={`fixed ${
          hasComparedCourses ? 'bottom-24 sm:bottom-6' : 'bottom-6'
        } right-4 sm:right-6 z-40 flex flex-col items-end transition-all duration-300`}
      >
        {/* Subtle pill hint when closed (collapsible) */}
        {!isOpen && (
          <button
            onClick={() => setIsOpen(true)}
            className="mb-2 hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-card/95 backdrop-blur-md border border-border shadow-md text-xs font-semibold text-foreground hover:border-primary/40 transition-all cursor-pointer group animate-in fade-in slide-in-from-bottom-2 duration-300"
          >
            <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
            <span className="text-[11px] text-muted-foreground group-hover:text-foreground">Admissions Desk</span>
            <span className="text-[10px] text-primary font-bold">Online</span>
          </button>
        )}

        {/* Main Floating Bubble */}
        <button
          ref={buttonRef}
          onClick={() => setIsOpen(!isOpen)}
          aria-expanded={isOpen}
          aria-label="Open PANIA Quick-WhatsApp Admissions Desk"
          className={`relative flex items-center justify-center p-3.5 sm:p-4 rounded-full shadow-lg transition-all duration-300 cursor-pointer ${
            isOpen
              ? 'bg-foreground text-background scale-95 shadow-md'
              : 'bg-[#25D366] hover:bg-[#20ba59] text-white hover:scale-105 shadow-emerald-500/20'
          }`}
          title="Quick WhatsApp Admissions Desk"
        >
          {isOpen ? (
            <X className="w-6 h-6" />
          ) : (
            <>
              <MessageCircle className="w-6 h-6 fill-current text-white" />
              {/* Pulsing online badge */}
              <span className="absolute -top-1 -right-1 flex h-3.5 w-3.5">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                <span className="relative inline-flex rounded-full h-3.5 w-3.5 bg-emerald-500 border-2 border-white dark:border-gray-900" />
              </span>
            </>
          )}
        </button>
      </div>

      {/* Floating Popover Desk */}
      {isOpen && (
        <div
          ref={popoverRef}
          role="dialog"
          aria-label="PANIA Quick WhatsApp Admissions Desk"
          className={`fixed ${
            hasComparedCourses ? 'bottom-40 sm:bottom-22' : 'bottom-22'
          } right-3 sm:right-6 z-40 w-[calc(100vw-1.5rem)] sm:w-[480px] md:w-[510px] max-h-[85vh] sm:max-h-[92vh] flex flex-col rounded-3xl bg-card border border-border shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200`}
        >
          {/* Desk Header */}
          <div className="p-4 sm:p-5 bg-primary text-primary-foreground relative">
            <div className="flex items-start justify-between gap-3">
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <span className="inline-block w-2.5 h-2.5 rounded-full bg-accent ring-4 ring-accent/30 animate-pulse" />
                  <span className="text-[11px] font-bold uppercase tracking-wider text-accent">
                    Online Admissions Desk
                  </span>
                </div>
                <h3 className="font-bold text-base sm:text-xl leading-tight">
                  PANIA Digital Academy
                </h3>
                <p className="text-xs text-primary-foreground/85 flex items-center gap-1.5 pt-0.5">
                  <Clock className="w-3.5 h-3.5 text-accent" />
                  <span>Nairobi Time (EAT / UTC+3) · Live Advisors Reply &lt; 15 mins</span>
                </p>
              </div>

              <button
                onClick={() => setIsOpen(false)}
                className="p-1.5 rounded-full text-primary-foreground/70 hover:text-primary-foreground hover:bg-white/10 transition cursor-pointer"
                aria-label="Close desk"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Scrollable Content Container */}
          <div className="p-4 sm:p-5 space-y-4 flex-1 overflow-y-auto max-h-[580px] scrollbar-thin">
            {/* Quick-Action Prompts in a neat 2-column grid */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-xs font-bold text-foreground flex items-center gap-1.5">
                  <Sparkles className="w-3.5 h-3.5 text-teal" />
                  <span>1-Tap Inquiry Topics:</span>
                </p>
                <span className="text-[11px] text-muted-foreground">Select to load message</span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {QUICK_PROMPTS.map((prompt) => {
                  const Icon = prompt.icon;
                  const isSelected = customMessage === prompt.message;

                  return (
                    <button
                      key={prompt.id}
                      onClick={() => handleSelectPrompt(prompt.message)}
                      className={`text-left p-2.5 rounded-xl border text-xs transition-all flex items-center justify-between gap-2 cursor-pointer group ${
                        isSelected
                          ? 'bg-accent/25 border-accent text-accent-foreground font-bold shadow-2xs ring-1 ring-accent/40'
                          : 'bg-secondary/60 hover:bg-secondary border-border/70 text-foreground/90 hover:text-foreground'
                      }`}
                    >
                      <div className="flex items-center gap-2 min-w-0">
                        <div
                          className={`w-6 h-6 rounded-lg flex items-center justify-center shrink-0 ${
                            isSelected
                              ? 'bg-primary text-primary-foreground'
                              : 'bg-card text-muted-foreground group-hover:text-primary'
                          }`}
                        >
                          <Icon className="w-3.5 h-3.5" />
                        </div>
                        <span className="truncate font-medium">{prompt.label}</span>
                      </div>

                      {prompt.badge && (
                        <span className="shrink-0 text-[9px] font-bold px-1.5 py-0.5 rounded bg-teal/15 text-teal border border-teal/20">
                          {prompt.badge}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Large, High-Legibility Message Area */}
            <div className="pt-2 border-t border-border/70 space-y-2">
              <div className="flex items-center justify-between">
                <label
                  htmlFor="wa-custom-msg"
                  className="text-xs sm:text-sm font-bold text-foreground flex items-center gap-1.5"
                >
                  <MessageCircle className="w-4 h-4 text-primary" />
                  <span>Your Message to Admissions Counselor</span>
                </label>

                {customMessage && (
                  <button
                    onClick={() => setCustomMessage('')}
                    className="text-[11px] text-muted-foreground hover:text-rose-500 font-medium transition cursor-pointer flex items-center gap-1"
                    title="Clear text"
                  >
                    <span>Clear text</span>
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>

              {/* Enhanced Spacious Textarea */}
              <div className="relative">
                <textarea
                  id="wa-custom-msg"
                  rows={5}
                  value={customMessage}
                  onChange={(e) => setCustomMessage(e.target.value)}
                  placeholder="Type your message clearly here, or click any topic above to load a pre-filled inquiry..."
                  className="w-full p-4 rounded-2xl bg-background border-2 border-border/80 text-foreground placeholder:text-muted-foreground/60 text-sm sm:text-base leading-relaxed focus:outline-none focus:border-[#25D366] focus:ring-4 focus:ring-[#25D366]/20 transition-all shadow-inner resize-y min-h-[140px] sm:min-h-[150px]"
                />
              </div>

              {/* Status and Hint */}
              <div className="flex items-center justify-between text-[11px] text-muted-foreground px-1">
                <span>
                  {customMessage ? (
                    <span className="text-teal font-medium flex items-center gap-1">
                      <span className="w-1.5 h-1.5 rounded-full bg-teal" />
                      Ready to send ({customMessage.length} characters)
                    </span>
                  ) : (
                    'Feel free to type your laptop specs, background, or questions'
                  )}
                </span>
                <span className="text-[10px] text-muted-foreground/75">Edit freely before sending</span>
              </div>

              {/* Large, Tactile Send Button */}
              <button
                onClick={() => handleSendToWhatsApp()}
                className="w-full inline-flex items-center justify-center gap-2.5 py-3.5 sm:py-4 px-5 rounded-2xl font-bold text-sm sm:text-base bg-[#25D366] hover:bg-[#20ba59] active:scale-[0.99] text-white transition-all shadow-md cursor-pointer mt-1"
              >
                <MessageCircle className="w-5 h-5 fill-current" />
                <span>Send to WhatsApp (+254 101 936 893)</span>
                <Send className="w-4 h-4 ml-0.5" />
              </button>
            </div>
          </div>

          {/* Footer note */}
          <div className="px-5 py-3 bg-secondary/80 border-t border-border/60 text-[11px] text-muted-foreground flex items-center justify-between">
            <span className="flex items-center gap-1.5">
              <ShieldCheck className="w-4 h-4 text-teal" />
              <span>Official PANIA Admissions Channel</span>
            </span>
            <a
              href="#faq"
              onClick={() => setIsOpen(false)}
              className="text-primary hover:underline font-semibold"
            >
              Browse 10+ FAQs
            </a>
          </div>
        </div>
      )}
    </>
  );
}
