import React, { useState, useMemo, useEffect } from 'react';
import {
  Search,
  ChevronDown,
  ChevronUp,
  MessageCircle,
  HelpCircle,
  Laptop,
  Clock,
  Briefcase,
  CreditCard,
  Award,
  Sparkles,
  X,
  Share2,
  Check,
  ArrowUpRight,
} from 'lucide-react';
import { Container, Eyebrow } from './Ui';
import { FAQS } from '../data/faqs';
import { FAQItem, FAQCategory } from '../types';
import { BRAND } from './Brand';

interface FaqAccordionProps {
  initialCategory?: FAQCategory | 'All';
  compact?: boolean;
  title?: string;
  subtitle?: string;
  onNavigate?: (path: string) => void;
  className?: string;
}

const CATEGORY_ICONS: Record<string, React.ElementType> = {
  All: HelpCircle,
  'Equipment & Tech': Laptop,
  'Schedule & Attendance': Clock,
  'Career Support & Jobs': Briefcase,
  'Tuition & Payment': CreditCard,
  'Certificates & Exams': Award,
  'Enrolment & Onboarding': Sparkles,
};

export function FaqAccordion({
  initialCategory = 'All',
  compact = false,
  title = 'Frequently Asked Questions',
  subtitle = 'Honest, detailed answers addressing the questions learners ask most before enrolling.',
  onNavigate,
  className = '',
}: FaqAccordionProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<FAQCategory | 'All'>(initialCategory);
  const [openIds, setOpenIds] = useState<string[]>(['faq-laptop-specs', 'faq-missed-zoom-recordings']);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // Available unique categories from data
  const categories: Array<FAQCategory | 'All'> = useMemo(() => {
    const set = new Set<FAQCategory>();
    FAQS.forEach((item) => {
      if (item.category) set.add(item.category);
    });
    return ['All', ...Array.from(set)];
  }, []);

  // Filtered FAQs based on category & search query
  const filteredFaqs = useMemo(() => {
    return FAQS.filter((faq) => {
      const matchesCategory =
        selectedCategory === 'All' || faq.category === selectedCategory;

      if (!matchesCategory) return false;

      if (!searchQuery.trim()) return true;

      const q = searchQuery.toLowerCase().trim();
      const matchQuestion = faq.question.toLowerCase().includes(q);
      const matchAnswer = faq.answer.toLowerCase().includes(q);
      const matchTags = faq.tags?.some((tag) => tag.toLowerCase().includes(q));

      return matchQuestion || matchAnswer || Boolean(matchTags);
    });
  }, [selectedCategory, searchQuery]);

  // Inject Schema.org FAQPage JSON-LD for rich snippet SEO
  useEffect(() => {
    const scriptId = 'faqpage-schema-jsonld';
    let scriptTag = document.getElementById(scriptId) as HTMLScriptElement | null;
    if (!scriptTag) {
      scriptTag = document.createElement('script');
      scriptTag.id = scriptId;
      scriptTag.type = 'application/ld+json';
      document.head.appendChild(scriptTag);
    }

    const faqSchema = {
      '@context': 'https://schema.org',
      '@type': 'FAQPage',
      mainEntity: FAQS.map((item) => ({
        '@type': 'Question',
        name: item.question,
        acceptedAnswer: {
          '@type': 'Answer',
          text: item.answer,
        },
      })),
    };

    scriptTag.textContent = JSON.stringify(faqSchema);

    return () => {
      const existing = document.getElementById(scriptId);
      if (existing) existing.remove();
    };
  }, []);

  const toggleItem = (id: string) => {
    setOpenIds((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const expandAll = () => {
    setOpenIds(filteredFaqs.map((f) => f.id));
  };

  const collapseAll = () => {
    setOpenIds([]);
  };

  const handleCopy = (id: string, text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const buildWhatsAppLinkForQuestion = (q: string) => {
    const prompt = `Hello PANIA Admissions, I have a question regarding: "${q}". Can you please advise?`;
    return `https://wa.me/254101936893?text=${encodeURIComponent(prompt)}`;
  };

  return (
    <section id="faq" className={`py-12 md:py-16 ${className}`}>
      <Container>
        {/* Header Block */}
        {!compact ? (
          <div className="max-w-3xl mx-auto text-center space-y-3 mb-10">
            <Eyebrow>Transparency & Objection Handling</Eyebrow>
            <h2 className="text-3xl sm:text-4xl font-bold text-foreground tracking-tight">
              {title}
            </h2>
            <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
              {subtitle}
            </p>
          </div>
        ) : (
          <div className="mb-6 space-y-1">
            <Eyebrow>Quick Answers</Eyebrow>
            <h3 className="text-2xl font-bold text-foreground">{title}</h3>
            <p className="text-xs text-muted-foreground">{subtitle}</p>
          </div>
        )}

        {/* Search Bar & Fast Query Pills */}
        <div className="max-w-3xl mx-auto mb-8 space-y-3">
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search questions (e.g., laptop specs, Zoom recordings, CV help, M-Pesa installments)..."
              className="w-full pl-11 pr-10 py-3.5 rounded-2xl bg-card border border-border text-sm text-foreground placeholder:text-muted-foreground/70 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary transition shadow-2xs"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3.5 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground transition rounded-full hover:bg-secondary cursor-pointer"
                title="Clear search"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          {/* Quick-suggest query tags */}
          <div className="flex flex-wrap items-center gap-1.5 text-xs">
            <span className="text-muted-foreground font-medium mr-1 text-[11px]">Popular:</span>
            {[
              { label: 'Laptop Specs', term: 'laptop' },
              { label: 'Zoom Recordings', term: 'recordings' },
              { label: 'CV & Job Linkages', term: 'CV' },
              { label: 'Installments', term: 'installments' },
              { label: 'Certificates', term: 'certificate' },
            ].map((tag) => (
              <button
                key={tag.label}
                onClick={() => setSearchQuery(tag.term)}
                className="px-2.5 py-1 rounded-full bg-secondary/80 hover:bg-secondary border border-border/70 text-foreground/80 hover:text-foreground transition text-[11px] cursor-pointer"
              >
                {tag.label}
              </button>
            ))}
          </div>
        </div>

        {/* Category Filter Tabs & Expand/Collapse Controls */}
        <div className="max-w-4xl mx-auto mb-8 space-y-3">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold uppercase tracking-wider text-teal flex items-center gap-1">
                <HelpCircle className="w-3.5 h-3.5" />
                <span>Filter by Topic:</span>
              </span>
            </div>

            {/* Expand/Collapse All Controls - Visible on ALL screens */}
            <div className="flex items-center gap-2">
              <button
                onClick={expandAll}
                className="min-h-[36px] px-3 py-1.5 rounded-full border border-border bg-card text-foreground hover:bg-secondary hover:text-primary transition-all cursor-pointer flex items-center gap-1.5 text-xs font-bold shadow-2xs"
                title="Expand all questions"
              >
                <ChevronDown className="w-3.5 h-3.5 text-primary" />
                <span>Expand All Questions</span>
              </button>
              <button
                onClick={collapseAll}
                className="min-h-[36px] px-3 py-1.5 rounded-full border border-border bg-card text-muted-foreground hover:bg-secondary hover:text-foreground transition-all cursor-pointer flex items-center gap-1.5 text-xs font-semibold"
                title="Collapse all questions"
              >
                <ChevronUp className="w-3.5 h-3.5" />
                <span>Collapse All</span>
              </button>
            </div>
          </div>

          {/* Category Filter Pills (Wrap neatly so none are hidden off-screen) */}
          <div className="flex flex-wrap items-center gap-2">
            {categories.map((cat) => {
              const Icon = CATEGORY_ICONS[cat] || HelpCircle;
              const count =
                cat === 'All'
                  ? FAQS.length
                  : FAQS.filter((f) => f.category === cat).length;
              const isSelected = selectedCategory === cat;
              const label = cat === 'All' ? 'All Questions' : cat;

              return (
                <button
                  key={cat}
                  onClick={() => setSelectedCategory(cat)}
                  aria-pressed={isSelected}
                  className={`inline-flex items-center gap-2 min-h-[40px] px-4 py-2 rounded-full text-xs font-bold transition-all cursor-pointer border shadow-2xs ${
                    isSelected
                      ? 'bg-primary text-primary-foreground border-primary shadow-xs'
                      : 'bg-card text-foreground border-border hover:bg-secondary hover:border-primary/40'
                  }`}
                >
                  <Icon className={`w-3.5 h-3.5 shrink-0 ${isSelected ? 'text-accent' : 'text-teal'}`} />
                  <span>{label}</span>
                  <span
                    className={`ml-1 text-[11px] font-bold px-2 py-0.5 rounded-full ${
                      isSelected
                        ? 'bg-accent text-accent-foreground'
                        : 'bg-secondary text-foreground'
                    }`}
                  >
                    {count}
                  </span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Accordion Items List */}
        <div className="max-w-3xl mx-auto space-y-4">
          {filteredFaqs.length === 0 ? (
            <div className="text-center py-12 px-6 rounded-3xl bg-secondary/50 border border-border space-y-3">
              <HelpCircle className="w-10 h-10 text-muted-foreground mx-auto" />
              <p className="font-bold text-foreground">No questions matching "{searchQuery}"</p>
              <p className="text-xs text-muted-foreground max-w-sm mx-auto">
                Have a specific requirement or question not listed here? Ask our admissions advisors directly on WhatsApp.
              </p>
              <div className="flex items-center justify-center gap-3 pt-2">
                <button
                  onClick={() => {
                    setSearchQuery('');
                    setSelectedCategory('All');
                  }}
                  className="px-4 py-2 rounded-full bg-card border border-border text-foreground text-xs font-bold hover:bg-secondary transition cursor-pointer"
                >
                  Reset FAQ Filter
                </button>
                <a
                  href={BRAND.whatsapp}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-accent text-accent-foreground text-xs font-bold hover:brightness-95 transition shadow-2xs"
                >
                  <MessageCircle className="w-4 h-4" />
                  <span>Ask Admissions on WhatsApp</span>
                </a>
              </div>
            </div>
          ) : (
            filteredFaqs.map((faq, idx) => {
              const isOpen = openIds.includes(faq.id);
              const isObjection = faq.isTopObjection;

              return (
                <div
                  key={faq.id}
                  className={`rounded-2xl border transition-all duration-200 overflow-hidden ${
                    isOpen
                      ? 'bg-card border-primary/40 shadow-sm ring-1 ring-primary/10'
                      : 'bg-card border-border hover:border-primary/30 hover:shadow-2xs'
                  } ${isObjection ? 'border-l-4 border-l-teal' : ''}`}
                >
                  {/* Accordion Trigger Button */}
                  <button
                    onClick={() => toggleItem(faq.id)}
                    aria-expanded={isOpen}
                    aria-controls={`faq-answer-${faq.id}`}
                    className="w-full text-left p-4 sm:p-5 flex items-start sm:items-center justify-between gap-4 cursor-pointer group hover:bg-secondary/20 transition-colors"
                  >
                    <div className="space-y-1.5 flex-1 pr-2">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-[11px] font-mono font-bold text-muted-foreground/80 px-2 py-0.5 rounded bg-secondary/80">
                          Q{idx + 1}
                        </span>
                        {isObjection && (
                          <span className="inline-flex items-center gap-1 text-[10px] font-black tracking-wide uppercase px-2 py-0.5 rounded-md bg-teal/15 text-teal border border-teal/30">
                            <Sparkles className="w-3 h-3" />
                            {faq.objectionLabel || 'Key Learner Question'}
                          </span>
                        )}
                        <span className="text-[10px] font-semibold text-muted-foreground hidden sm:inline">
                          {faq.category}
                        </span>
                      </div>
                      <h4
                        className={`text-base sm:text-lg font-bold transition-colors leading-snug ${
                          isOpen ? 'text-primary' : 'text-foreground group-hover:text-primary'
                        }`}
                      >
                        {faq.question}
                      </h4>
                    </div>

                    {/* Highly Visible Action Button */}
                    <div
                      className={`min-h-[38px] px-3.5 py-1.5 rounded-full text-xs font-bold flex items-center gap-1.5 transition-all shrink-0 shadow-2xs ${
                        isOpen
                          ? 'bg-primary text-primary-foreground shadow-xs'
                          : 'bg-primary/10 text-primary border border-primary/25 group-hover:bg-primary group-hover:text-primary-foreground'
                      }`}
                    >
                      <span className="text-xs font-bold">{isOpen ? 'Close' : 'View Answer'}</span>
                      <ChevronDown
                        className={`w-4 h-4 transition-transform duration-200 ${
                          isOpen ? 'rotate-180' : ''
                        }`}
                        aria-hidden="true"
                      />
                    </div>
                  </button>

                  {/* Accordion Body */}
                  {isOpen && (
                    <div
                      id={`faq-answer-${faq.id}`}
                      className="px-5 pb-5 pt-2 text-sm text-foreground/90 leading-relaxed border-t border-border/50 space-y-4 animate-in fade-in-50 duration-150 bg-secondary/15"
                    >
                      <p className="whitespace-pre-line text-foreground/95 font-normal leading-relaxed">
                        {faq.answer}
                      </p>

                      {/* Footer Actions inside Accordion */}
                      <div className="flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-border/40 text-xs">
                        <div className="flex items-center gap-2">
                          <span className="text-[11px] text-muted-foreground font-semibold">
                            Category: {faq.category}
                          </span>
                        </div>

                        <div className="flex items-center gap-2 flex-wrap">
                          <button
                            onClick={() => toggleItem(faq.id)}
                            className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-card hover:bg-secondary text-foreground text-[11px] font-semibold transition border border-border cursor-pointer"
                          >
                            <ChevronUp className="w-3 h-3" />
                            <span>Collapse</span>
                          </button>

                          <button
                            onClick={() => handleCopy(faq.id, `${faq.question}\n\n${faq.answer}`)}
                            className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-secondary hover:bg-secondary/80 text-foreground text-[11px] font-semibold transition cursor-pointer"
                            title="Copy question & answer"
                          >
                            {copiedId === faq.id ? (
                              <>
                                <Check className="w-3 h-3 text-teal" />
                                <span>Copied!</span>
                              </>
                            ) : (
                              <>
                                <Share2 className="w-3 h-3 text-muted-foreground" />
                                <span>Copy Answer</span>
                              </>
                            )}
                          </button>

                          <a
                            href={buildWhatsAppLinkForQuestion(faq.question)}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-accent/25 hover:bg-accent/40 text-accent-foreground text-[11px] font-bold transition border border-accent/40"
                          >
                            <MessageCircle className="w-3 h-3 text-primary" />
                            <span>Ask about this on WhatsApp</span>
                            <ArrowUpRight className="w-2.5 h-2.5 opacity-60" />
                          </a>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>

        {/* Bottom Direct Objection-Buster Box */}
        <div className="max-w-3xl mx-auto mt-10 p-6 rounded-3xl bg-primary text-primary-foreground flex flex-col sm:flex-row items-center justify-between gap-6 shadow-md border border-primary/20">
          <div className="space-y-1.5 text-center sm:text-left">
            <div className="flex items-center justify-center sm:justify-start gap-2">
              <span className="w-2.5 h-2.5 rounded-full bg-accent ring-4 ring-accent/30 animate-pulse" />
              <span className="text-xs uppercase font-bold tracking-wider text-accent">
                Admissions Desk Online (Nairobi EAT)
              </span>
            </div>
            <h3 className="text-lg sm:text-xl font-bold">Have an unlisted question or unique background?</h3>
            <p className="text-xs sm:text-sm text-primary-foreground/80 max-w-lg">
              Speak 1-on-1 with a PANIA academic advisor on WhatsApp. We provide honest prerequisite appraisals and custom roadmap recommendations.
            </p>
          </div>

          <div className="flex flex-col sm:flex-row items-center gap-2.5 shrink-0 w-full sm:w-auto">
            <a
              href={BRAND.whatsapp}
              target="_blank"
              rel="noreferrer"
              className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-5 py-3 rounded-full bg-accent text-accent-foreground text-xs font-bold hover:brightness-95 transition shadow-xs cursor-pointer"
            >
              <MessageCircle className="w-4 h-4 text-primary" />
              <span>Chat on WhatsApp</span>
            </a>
            {onNavigate && (
              <button
                onClick={() => onNavigate('/contact?mode=guidance')}
                className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-4 py-3 rounded-full bg-white/10 hover:bg-white/20 text-white text-xs font-semibold transition cursor-pointer"
              >
                <span>Request Callback</span>
              </button>
            )}
          </div>
        </div>
      </Container>
    </section>
  );
}
