import { AnimatePresence, motion } from 'framer-motion';
import { ArrowRight, BookOpen, Calendar, HelpCircle, Search, Shield, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { ALL_FAQS, EVENTS, SERVICES, STORIES } from '../../data/content';

interface GlobalSearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function GlobalSearchModal({ isOpen, onClose }: GlobalSearchModalProps) {
  const [query, setQuery] = useState('');

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        if (isOpen) onClose();
        else setQuery('');
      }
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const trimmed = query.trim().toLowerCase();

  const matchingServices = trimmed
    ? SERVICES.filter(
        (s) =>
          s.title.toLowerCase().includes(trimmed) ||
          s.short.toLowerCase().includes(trimmed) ||
          s.description.toLowerCase().includes(trimmed),
      )
    : SERVICES.slice(0, 4);

  const matchingFaqs = trimmed
    ? ALL_FAQS.filter(
        (f) => f.q.toLowerCase().includes(trimmed) || f.a.toLowerCase().includes(trimmed),
      )
    : ALL_FAQS.slice(0, 3);

  const matchingEvents = trimmed
    ? EVENTS.filter(
        (e) =>
          e.title.toLowerCase().includes(trimmed) ||
          e.summary.toLowerCase().includes(trimmed) ||
          e.location.toLowerCase().includes(trimmed),
      )
    : EVENTS;

  const matchingStories = trimmed
    ? STORIES.filter(
        (st) =>
          st.name.toLowerCase().includes(trimmed) ||
          st.quote.toLowerCase().includes(trimmed) ||
          st.role.toLowerCase().includes(trimmed),
      )
    : [];

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-[100] flex items-start justify-center p-4 pt-16 sm:pt-24 bg-black/60 backdrop-blur-sm">
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: -20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: -20 }}
          className="w-full max-w-2xl overflow-hidden rounded-2xl border border-theme bg-[var(--color-surface)] shadow-2xl"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header Input */}
          <div className="flex items-center gap-3 border-b border-theme px-4 py-3.5">
            <Search className="h-5 w-5 text-primary shrink-0" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search services, NDIS guides, FAQs, events..."
              className="w-full bg-transparent text-base text-[var(--color-text)] outline-none placeholder:text-muted"
              autoFocus
            />
            {query && (
              <button
                type="button"
                onClick={() => setQuery('')}
                className="text-xs text-muted hover:text-[var(--color-text)] underline px-1"
              >
                Clear
              </button>
            )}
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg p-1.5 text-muted hover:bg-[color-mix(in_srgb,var(--color-primary)_10%,transparent)] hover:text-[var(--color-text)]"
              aria-label="Close search"
            >
              <X className="h-5 w-5" />
            </button>
          </div>

          {/* Body Results */}
          <div className="max-h-[60vh] overflow-y-auto p-4 space-y-6">
            {/* Services Section */}
            <div>
              <div className="flex items-center gap-2 mb-2 text-xs font-bold uppercase tracking-wider text-muted">
                <Shield className="h-3.5 w-3.5 text-primary" /> Services ({matchingServices.length})
              </div>
              <div className="grid gap-2">
                {matchingServices.map((s) => (
                  <Link
                    key={s.slug}
                    to={`/services/${s.slug}`}
                    onClick={onClose}
                    className="group flex items-center justify-between rounded-xl border border-theme p-3 transition-colors hover:bg-[color-mix(in_srgb,var(--color-primary)_8%,transparent)]"
                  >
                    <div>
                      <p className="font-semibold text-sm text-[var(--color-text)] group-hover:text-primary">
                        {s.title}
                      </p>
                      <p className="text-xs text-muted line-clamp-1">{s.short} — {s.description}</p>
                    </div>
                    <ArrowRight className="h-4 w-4 text-muted transition-transform group-hover:translate-x-1 group-hover:text-primary shrink-0" />
                  </Link>
                ))}
              </div>
            </div>

            {/* FAQs Section */}
            {matchingFaqs.length > 0 && (
              <div>
                <div className="flex items-center gap-2 mb-2 text-xs font-bold uppercase tracking-wider text-muted">
                  <HelpCircle className="h-3.5 w-3.5 text-primary" /> FAQs ({matchingFaqs.length})
                </div>
                <div className="grid gap-2">
                  {matchingFaqs.map((f, i) => (
                    <Link
                      key={i}
                      to="/ndis-hub/faq"
                      onClick={onClose}
                      className="group block rounded-xl border border-theme p-3 transition-colors hover:bg-[color-mix(in_srgb,var(--color-primary)_8%,transparent)]"
                    >
                      <p className="font-semibold text-xs text-[var(--color-text)] group-hover:text-primary">
                        {f.q}
                      </p>
                      <p className="text-xs text-muted line-clamp-1 mt-0.5">{f.a}</p>
                    </Link>
                  ))}
                </div>
              </div>
            )}

            {/* Events Section */}
            {matchingEvents.length > 0 && (
              <div>
                <div className="flex items-center gap-2 mb-2 text-xs font-bold uppercase tracking-wider text-muted">
                  <Calendar className="h-3.5 w-3.5 text-primary" /> Events ({matchingEvents.length})
                </div>
                <div className="grid gap-2">
                  {matchingEvents.map((ev) => (
                    <Link
                      key={ev.id}
                      to="/events"
                      onClick={onClose}
                      className="group flex items-center justify-between rounded-xl border border-theme p-3 transition-colors hover:bg-[color-mix(in_srgb,var(--color-primary)_8%,transparent)]"
                    >
                      <div>
                        <p className="font-semibold text-xs text-[var(--color-text)] group-hover:text-primary">
                          {ev.title}
                        </p>
                        <p className="text-[11px] text-muted">{ev.date} · {ev.location}</p>
                      </div>
                      <span className="text-xs font-medium text-primary">RSVP →</span>
                    </Link>
                  ))}
                </div>
              </div>
            )}

            {/* Stories Section */}
            {matchingStories.length > 0 && (
              <div>
                <div className="flex items-center gap-2 mb-2 text-xs font-bold uppercase tracking-wider text-muted">
                  <BookOpen className="h-3.5 w-3.5 text-primary" /> Participant Stories
                </div>
                <div className="grid gap-2">
                  {matchingStories.map((st) => (
                    <Link
                      key={st.id}
                      to="/ndis-hub/stories"
                      onClick={onClose}
                      className="group block rounded-xl border border-theme p-3 transition-colors hover:bg-[color-mix(in_srgb,var(--color-primary)_8%,transparent)]"
                    >
                      <p className="font-semibold text-xs text-[var(--color-text)]">
                        {st.name} ({st.role})
                      </p>
                      <p className="text-xs text-muted italic line-clamp-1">"{st.quote}"</p>
                    </Link>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Footer Shortcuts */}
          <div className="flex items-center justify-between border-t border-theme px-4 py-2 text-[11px] text-muted bg-[var(--color-bg)]">
            <span>
              Tip: Press <kbd className="px-1.5 py-0.5 rounded border border-theme bg-surface font-mono">ESC</kbd> to exit
            </span>
            <span>
              Press <kbd className="px-1.5 py-0.5 rounded border border-theme bg-surface font-mono">Ctrl+K</kbd> anytime
            </span>
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  );
}
