import { AnimatePresence, motion } from 'framer-motion';
import { ChevronDown, HelpCircle, PhoneCall, Search } from 'lucide-react';
import { useState } from 'react';
import { FAQ_CATEGORIES, SITE } from '../data/content';
import { PageHero } from '../components/ui/SectionHeading';
import { FadeIn } from '../components/ui/Motion';
import { LinkButton } from '../components/ui/Button';

export function FaqPage() {
  const [activeCategory, setActiveCategory] = useState<string>('all');
  const [search, setSearch] = useState('');
  const [openIndex, setOpenIndex] = useState<string | null>('general-0');

  const categories = [
    { id: 'all', label: 'All Questions' },
    ...FAQ_CATEGORIES.map((c) => ({ id: c.id, label: c.name })),
  ];

  const itemsToDisplay = FAQ_CATEGORIES.flatMap((cat) =>
    cat.items.map((item, idx) => ({
      key: `${cat.id}-${idx}`,
      category: cat.id,
      categoryName: cat.name,
      ...item,
    })),
  ).filter((item) => {
    const matchesCat = activeCategory === 'all' || item.category === activeCategory;
    const q = search.trim().toLowerCase();
    const matchesSearch = !q || item.q.toLowerCase().includes(q) || item.a.toLowerCase().includes(q);
    return matchesCat && matchesSearch;
  });

  return (
    <>
      <PageHero
        title="Frequently Asked Questions"
        subtitle="Clear, straightforward answers about NDIS funding, eligibility, price guides, and support options."
      />

      <section className="px-4 py-16">
        <div className="mx-auto max-w-4xl space-y-8">
          {/* Controls */}
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-theme pb-6">
            <div className="flex flex-wrap gap-2">
              {categories.map((cat) => (
                <button
                  key={cat.id}
                  type="button"
                  onClick={() => setActiveCategory(cat.id)}
                  className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition-all ${
                    activeCategory === cat.id
                      ? 'bg-primary text-white shadow-md'
                      : 'bg-surface border border-theme text-muted hover:border-primary'
                  }`}
                >
                  {cat.label}
                </button>
              ))}
            </div>

            <div className="relative w-full sm:w-64">
              <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search FAQ..."
                className="w-full rounded-xl border border-theme bg-surface pl-9 pr-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* FAQ Accordion List */}
          {itemsToDisplay.length === 0 ? (
            <div className="py-12 text-center rounded-3xl border border-dashed border-theme p-6">
              <p className="font-bold text-sm text-[var(--color-text)]">No questions matched your search.</p>
              <button
                type="button"
                onClick={() => {
                  setSearch('');
                  setActiveCategory('all');
                }}
                className="mt-2 text-xs text-primary font-bold underline"
              >
                Reset Search Filters
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {itemsToDisplay.map((item) => {
                const isOpen = openIndex === item.key;
                return (
                  <FadeIn key={item.key}>
                    <div className="overflow-hidden rounded-2xl border border-theme bg-[var(--color-surface)] shadow-sm transition-colors hover:border-primary/50">
                      <button
                        type="button"
                        className="flex w-full items-center justify-between gap-4 px-6 py-4 text-left font-bold text-sm text-[var(--color-text)]"
                        onClick={() => setOpenIndex(isOpen ? null : item.key)}
                        aria-expanded={isOpen}
                      >
                        <span className="flex items-center gap-2">
                          <HelpCircle className="h-4 w-4 text-primary shrink-0" />
                          {item.q}
                        </span>
                        <ChevronDown
                          className={`h-4 w-4 shrink-0 text-primary transition-transform ${
                            isOpen ? 'rotate-180' : ''
                          }`}
                        />
                      </button>

                      <AnimatePresence initial={false}>
                        {isOpen && (
                          <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: 'auto', opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            transition={{ duration: 0.2 }}
                          >
                            <p className="border-t border-theme px-6 py-4 text-xs leading-relaxed text-muted bg-[var(--color-bg)]">
                              {item.a}
                            </p>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </div>
                  </FadeIn>
                );
              })}
            </div>
          )}

          {/* Bottom Help Banner */}
          <FadeIn className="mt-12 rounded-3xl border border-theme bg-[var(--color-bg-alt)] p-8 text-center shadow-lg space-y-4">
            <h3 className="text-xl font-bold text-[var(--color-text)]">Still Have Questions About Your NDIS Plan?</h3>
            <p className="text-xs text-muted max-w-md mx-auto">
              Our local intake specialists are standing by to guide you through funding options and service agreements.
            </p>
            <div className="flex flex-wrap justify-center gap-4 pt-2">
              <LinkButton to="/contact#book">Book A Free Consultation</LinkButton>
              <a
                href={`tel:${SITE.phone.replace(/\s/g, '')}`}
                className="inline-flex items-center gap-2 rounded-full border border-theme px-4 py-2 text-xs font-bold text-[var(--color-text)] hover:bg-surface"
              >
                <PhoneCall className="h-4 w-4 text-primary" /> Call Intake: {SITE.phone}
              </a>
            </div>
          </FadeIn>
        </div>
      </section>
    </>
  );
}

