'use client';

import { useState, useEffect, useRef, useMemo } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { Search, X, FileText } from 'lucide-react';
import type { DocsLocale, NavGroup } from '@/lib/docs-types';
import styles from './DocsSearch.module.css';

type DocsSearchProps = {
  placeholder?: string;
  locale?: DocsLocale;
  docsNavigation: NavGroup[];
};


type SearchResult = {
  id: string;
  slug: string;
  title: string;
  category: string;
  href: string;
};

export default function DocsSearch({ placeholder, locale = 'en', docsNavigation }: DocsSearchProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();
  const pathname = usePathname();

  // Extract locale from pathname
  const currentLocale = (pathname?.split('/')[1] as DocsLocale) || locale;


  // Build search index from navigation
  const searchIndex: SearchResult[] = useMemo(() => docsNavigation.flatMap(group =>
    group.items.map(item => ({
      id: item.id,
      slug: item.slug,
      title: item.label[currentLocale],
      category: group.label[currentLocale],
      href: `/${currentLocale}/docs/${item.slug}`
    }))
  ), [currentLocale, docsNavigation]);

  // Calculate search results using useMemo instead of useEffect
  const results = useMemo(() => {
    if (!query.trim()) {
      return [];
    }

    const searchTerm = query.toLowerCase().trim();
    const filtered = searchIndex.filter(item => {
      const titleMatch = item.title.toLowerCase().includes(searchTerm);
      const categoryMatch = item.category.toLowerCase().includes(searchTerm);
      const slugMatch = item.slug.toLowerCase().includes(searchTerm);
      return titleMatch || categoryMatch || slugMatch;
    });

    // Sort by relevance (title matches first)
    const sorted = filtered.sort((a, b) => {
      const aTitleMatch = a.title.toLowerCase().startsWith(searchTerm);
      const bTitleMatch = b.title.toLowerCase().startsWith(searchTerm);
      if (aTitleMatch && !bTitleMatch) return -1;
      if (!aTitleMatch && bTitleMatch) return 1;
      return a.title.localeCompare(b.title);
    });

    return sorted.slice(0, 10); // Limit to 10 results
  }, [query, searchIndex]);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Cmd/Ctrl + K to open
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setIsOpen(true);
      }

      // Escape to close
      if (e.key === 'Escape' && isOpen) {
        setIsOpen(false);
        setQuery('');
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen]);

  // Focus input when modal opens
  useEffect(() => {
    if (isOpen && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen]);

  // Handle navigation
  const handleSelect = (result: SearchResult) => {
    router.push(result.href);
    setIsOpen(false);
    setQuery('');
  };

  // Handle keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSelectedIndex(prev => Math.min(prev + 1, results.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSelectedIndex(prev => Math.max(prev - 1, 0));
    } else if (e.key === 'Enter' && results[selectedIndex]) {
      e.preventDefault();
      handleSelect(results[selectedIndex]);
    }
  };

  return (
    <>
      <button
        className={styles.searchButton}
        type="button"
        onClick={() => setIsOpen(true)}
        aria-label="Search documentation"
      >
        <div className={styles.searchContent}>
          <Search size={16} />
          <span>{placeholder ?? 'Search documentation…'}</span>
        </div>
        <div className={styles.searchShortcut}>
          <span>⌘</span>
          <span>K</span>
        </div>
      </button>

      {isOpen && (
        <>
          <div className={styles.overlay} onClick={() => setIsOpen(false)} />
          <div className={styles.modal}>
            <div className={styles.searchInputWrapper}>
              <Search size={20} className={styles.searchIcon} />
              <input
                ref={inputRef}
                type="text"
                className={styles.searchInput}
                placeholder={placeholder ?? 'Search documentation…'}
                value={query}
                onChange={(e) => {
                  setQuery(e.target.value);
                  setSelectedIndex(0); // Reset selected index when query changes
                }}
                onKeyDown={handleKeyDown}
              />
              <button
                className={styles.closeButton}
                onClick={() => setIsOpen(false)}
                aria-label="Close search"
              >
                <X size={18} />
              </button>
            </div>

            {query && (
              <div className={styles.results}>
                {results.length > 0 ? (
                  <ul className={styles.resultsList}>
                    {results.map((result, index) => (
                      <li key={result.id}>
                        <button
                          className={`${styles.resultItem} ${index === selectedIndex ? styles.resultItemActive : ''
                            }`}
                          onClick={() => handleSelect(result)}
                        >
                          <FileText size={16} className={styles.resultIcon} />
                          <div className={styles.resultContent}>
                            <div className={styles.resultTitle}>{result.title}</div>
                            <div className={styles.resultCategory}>{result.category}</div>
                          </div>
                        </button>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <div className={styles.noResults}>
                    <p>No results found for &quot;{query}&quot;</p>
                  </div>
                )}
              </div>
            )}

            {!query && (
              <div className={styles.emptyState}>
                <p>Type to search documentation...</p>
              </div>
            )}
          </div>
        </>
      )}
    </>
  );
}

