'use client'

import { useState, useEffect, useRef } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Search, X, FileText, ArrowRight, Loader2 } from 'lucide-react'
import Link from 'next/link'
import { pagesApi, Page, searchApi, SearchResult } from '@/lib/api'

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

interface StaticPage {
  title: string
  slug: string
  url: string
  category?: string
}

// Static pages that exist in the app directory
const staticPages: StaticPage[] = [
  { title: 'About Us', slug: 'about', url: '/about' },
  { title: 'Executive Mayor', slug: 'executive-mayor', url: '/council/executive-mayor' },
  { title: 'Municipal Council', slug: 'municipal-council', url: '/council/municipal-council' },
  { title: 'Office of the single Whip', slug: 'office-single-whip', url: '/council/office-single-whip' },
  { title: 'Members of the Mayoral Committee', slug: 'members-mayoral-committee', url: '/council/members-mayoral-committee' },
  { title: 'MPAC', slug: 'mpac', url: '/council/mpac' },
  { title: 'Speaker of Council', slug: 'speaker-council', url: '/council/speaker-council' },
  { title: 'Ward Committees', slug: 'ward-committees', url: '/council/ward-committees' },
  { title: 'Accounts', slug: 'accounts', url: '/services/accounts' },
  { title: 'Building Plans', slug: 'building-plans', url: '/services/building-plans' },
  { title: 'Cemetery & Hall', slug: 'cemetery-hall', url: '/services/cemetery-hall' },
  { title: 'Electricity', slug: 'electricity', url: '/services/electricity' },
  { title: 'Fire and Disaster Services', slug: 'fire-disaster-services', url: '/services/fire-disaster-services' },
  { title: 'Housing', slug: 'housing', url: '/services/housing' },
  { title: 'Refuse Collection', slug: 'refuse-collection', url: '/services/refuse-collection' },
  { title: 'Traffic', slug: 'traffic', url: '/services/traffic' },
  { title: 'Transport, Roads and Robots', slug: 'transport-roads-robots', url: '/services/transport-roads-robots' },
  { title: 'Water & Sanitation Services', slug: 'water-sanitation-services', url: '/services/water-sanitation-services' },
  { title: 'Contact Us', slug: 'contact', url: '/contact' },
  { title: 'News', slug: 'news', url: '/news' },
  { title: 'Events', slug: 'events', url: '/events' },
  { title: 'Tenders', slug: 'tenders', url: '/tenders' },
  { title: 'Vacancies', slug: 'vacancies', url: '/vacancies' },
]

export default function SearchDialog({ isOpen, onClose }: SearchDialogProps) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<{
    staticPages: StaticPage[]
    dynamicPages: Page[]
  }>({ staticPages: [], dynamicPages: [] })
  const [loading, setLoading] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus()
    }
  }, [isOpen])

  useEffect(() => {
    const performSearch = async () => {
      if (!query.trim()) {
        setResults({ staticPages: [], dynamicPages: [] })
        return
      }

      setLoading(true)
      const searchTerm = query.toLowerCase().trim()

      // Search static pages
      const staticResults = staticPages.filter(page =>
        page.title.toLowerCase().includes(searchTerm) ||
        page.slug.toLowerCase().includes(searchTerm)
      )

      // Search dynamic pages from API
      let dynamicResults: Page[] = []
      try {
        const allPages = await pagesApi.getAll()
        dynamicResults = allPages.filter(page =>
          page.title.toLowerCase().includes(searchTerm) ||
          page.slug.toLowerCase().includes(searchTerm) ||
          (page.excerpt && page.excerpt.toLowerCase().includes(searchTerm))
        )
      } catch (error) {
        console.error('Error fetching pages:', error)
      }

      setResults({
        staticPages: staticResults,
        dynamicPages: dynamicResults
      })
      setLoading(false)
    }

    const timeoutId = setTimeout(() => {
      performSearch()
    }, 300) // Debounce search

    return () => clearTimeout(timeoutId)
  }, [query])

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    if (isOpen) {
      document.addEventListener('keydown', handleEscape)
      document.body.style.overflow = 'hidden'
    }

    return () => {
      document.removeEventListener('keydown', handleEscape)
      document.body.style.overflow = 'unset'
    }
  }, [isOpen, onClose])

  const highlightText = (text: string, searchQuery: string) => {
    if (!searchQuery) return text
    const regex = new RegExp(`(${searchQuery})`, 'gi')
    const parts = text.split(regex)
    return (
      <>
        {parts.map((part, index) =>
          regex.test(part) ? (
            <mark key={index} className="bg-primary/30 text-white px-1 rounded">
              {part}
            </mark>
          ) : (
            part
          )
        )}
      </>
    )
  }

  const totalResults = results.staticPages.length + results.dynamicPages.length

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100]"
          />

          {/* Dialog */}
          <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 }}
            transition={{ duration: 0.2 }}
            className="fixed inset-0 z-[101] flex items-start justify-center pt-20 px-4"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="w-full max-w-2xl glass-page rounded-2xl shadow-2xl overflow-hidden">
              {/* Header */}
              <div className="p-6 border-b border-white/10">
                <div className="flex items-center gap-4">
                  <div className="relative flex-1">
                    <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-white/50 w-5 h-5" />
                    <input
                      ref={inputRef}
                      type="text"
                      value={query}
                      onChange={(e) => setQuery(e.target.value)}
                      placeholder="Search pages..."
                      className="w-full px-6 py-3 pl-14 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    />
                    {loading && (
                      <div className="absolute right-4 top-1/2 transform -translate-y-1/2">
                        <Loader2 className="w-5 h-5 text-primary animate-spin" />
                      </div>
                    )}
                  </div>
                  <button
                    onClick={onClose}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    aria-label="Close search"
                  >
                    <X className="w-6 h-6 text-white" />
                  </button>
                </div>
              </div>

              {/* Results */}
              <div className="max-h-[60vh] overflow-y-auto">
                {query.trim() ? (
                  loading ? (
                    <div className="p-8 text-center text-white/50">
                      <Loader2 className="w-8 h-8 mx-auto mb-4 animate-spin text-primary" />
                      <p>Searching...</p>
                    </div>
                  ) : totalResults > 0 ? (
                    <div className="p-6 space-y-6">
                      {/* Static Pages */}
                      {results.staticPages.length > 0 && (
                        <div>
                          <div className="flex items-center gap-2 mb-4">
                            <FileText className="text-primary w-5 h-5" />
                            <h3 className="text-lg font-bold text-white">
                              Pages ({results.staticPages.length})
                            </h3>
                          </div>
                          <div className="space-y-2">
                            {results.staticPages.map((page) => (
                              <Link
                                key={page.slug}
                                href={page.url}
                                onClick={onClose}
                                className="block glass rounded-lg p-4 hover:bg-white/10 transition-all"
                              >
                                <div className="flex items-center justify-between">
                                  <h4 className="text-base font-semibold text-white">
                                    {highlightText(page.title, query)}
                                  </h4>
                                  <ArrowRight className="w-4 h-4 text-primary flex-shrink-0" />
                                </div>
                              </Link>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* Dynamic Pages */}
                      {results.dynamicPages.length > 0 && (
                        <div>
                          <div className="flex items-center gap-2 mb-4">
                            <FileText className="text-primary w-5 h-5" />
                            <h3 className="text-lg font-bold text-white">
                              Content Pages ({results.dynamicPages.length})
                            </h3>
                          </div>
                          <div className="space-y-2">
                            {results.dynamicPages.map((page) => (
                              <Link
                                key={page._id}
                                href={`/${page.slug}`}
                                onClick={onClose}
                                className="block glass rounded-lg p-4 hover:bg-white/10 transition-all"
                              >
                                <div className="flex items-center justify-between">
                                  <div className="flex-1">
                                    <h4 className="text-base font-semibold text-white mb-1">
                                      {highlightText(page.title, query)}
                                    </h4>
                                    {page.excerpt && (
                                      <p className="text-white/70 text-sm">
                                        {highlightText(page.excerpt.substring(0, 100), query)}
                                        {page.excerpt.length > 100 && '...'}
                                      </p>
                                    )}
                                  </div>
                                  <ArrowRight className="w-4 h-4 text-primary flex-shrink-0 ml-4" />
                                </div>
                              </Link>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="p-8 text-center">
                      <p className="text-white/70 mb-2">No results found</p>
                      <p className="text-white/50 text-sm">Try different keywords</p>
                    </div>
                  )
                ) : (
                  <div className="p-8 text-center text-white/50">
                    <Search className="w-12 h-12 mx-auto mb-4 opacity-50" />
                    <p>Start typing to search pages</p>
                  </div>
                )}
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}
