import React, { useState, useEffect, useRef } from 'react';
import { Search, X, ArrowRight, CornerDownLeft } from 'lucide-react';
import { searchCourses, SUBJECTS, ZiteCourse } from '../data/courses';

interface SearchDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onNavigate: (path: string) => void;
}

export function SearchDialog({ open, onOpenChange, onNavigate }: SearchDialogProps) {
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);

  const results = searchCourses(query).slice(0, 8);

  useEffect(() => {
    if (open) {
      setQuery('');
      setSelectedIndex(0);
      const originalOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      setTimeout(() => inputRef.current?.focus(), 50);
      return () => {
        document.body.style.overflow = originalOverflow;
      };
    }
  }, [open]);

  useEffect(() => {
    setSelectedIndex(0);
  }, [query]);

  // Global keyboard shortcut ⌘K / Ctrl+K
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        onOpenChange(!open);
      }
      if (open && e.key === 'Escape') {
        e.preventDefault();
        onOpenChange(false);
      }
    };

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

  if (!open) return null;

  const handleSelect = (course: ZiteCourse) => {
    onOpenChange(false);
    onNavigate(`/programmes/${course.slug}`);
  };

  const handleSearchAll = () => {
    onOpenChange(false);
    onNavigate(`/programmes?q=${encodeURIComponent(query)}`);
  };

  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') {
      e.preventDefault();
      if (results[selectedIndex]) {
        handleSelect(results[selectedIndex]);
      } else if (query.trim()) {
        handleSearchAll();
      }
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center pt-20 p-4 bg-slate-950/60 backdrop-blur-xs animate-in fade-in duration-150"
      onClick={() => onOpenChange(false)}
      role="dialog"
      aria-modal="true"
      aria-label="Search programmes"
    >
      <div
        className="w-full max-w-xl bg-card text-foreground rounded-2xl shadow-2xl border border-border overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Search Input Bar */}
        <div className="flex items-center gap-3 px-5 py-4 border-b border-border">
          <Search className="h-5 w-5 text-muted-foreground shrink-0" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Search courses, subjects or providers — try GCP or VA"
            className="flex-1 bg-transparent outline-none text-base text-foreground placeholder:text-muted-foreground"
            role="combobox"
            aria-expanded="true"
            aria-controls="search-results"
          />
          {query ? (
            <button
              onClick={() => setQuery('')}
              className="p-1 text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          ) : (
            <kbd className="hidden sm:inline-block px-2 py-0.5 text-xs text-muted-foreground bg-secondary rounded border border-border">
              ESC
            </kbd>
          )}
        </div>

        {/* Results List */}
        <ul id="search-results" role="listbox" className="max-h-80 overflow-y-auto divide-y divide-border/60">
          {results.length > 0 ? (
            results.map((c, idx) => {
              const isSelected = idx === selectedIndex;
              const meta = SUBJECTS[c.subject];
              return (
                <li
                  key={c.code}
                  role="option"
                  aria-selected={isSelected}
                  onClick={() => handleSelect(c)}
                  onMouseEnter={() => setSelectedIndex(idx)}
                  className={`px-5 py-3.5 flex items-center justify-between gap-4 cursor-pointer transition-colors ${
                    isSelected ? 'bg-secondary' : 'hover:bg-secondary/50'
                  }`}
                >
                  <div className="flex items-center gap-3 overflow-hidden">
                    <span className={`w-2.5 h-2.5 rounded-full shrink-0 ${meta.bgSolid}`} />
                    <div className="truncate">
                      <p className="text-sm font-bold text-foreground truncate">{c.title}</p>
                      <p className="text-xs text-muted-foreground truncate">
                        {meta.label} · {c.provider}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 shrink-0">
                    <span className={`text-[11px] font-semibold px-2 py-0.5 rounded-full ${meta.bgSoft} ${meta.textColor}`}>
                      {c.provider}
                    </span>
                    {isSelected && <CornerDownLeft className="h-3.5 w-3.5 text-muted-foreground" />}
                  </div>
                </li>
              );
            })
          ) : (
            <li className="px-5 py-8 text-center text-sm text-muted-foreground">
              No matching courses found for &ldquo;{query}&rdquo;.
            </li>
          )}
        </ul>

        {/* Footer shortcuts */}
        <div className="px-5 py-3 bg-secondary/50 border-t border-border flex items-center justify-between text-xs text-muted-foreground">
          <div className="flex items-center gap-3">
            <span>
              <kbd className="font-mono bg-card px-1.5 py-0.5 rounded border border-border">↑</kbd>{' '}
              <kbd className="font-mono bg-card px-1.5 py-0.5 rounded border border-border">↓</kbd> navigate
            </span>
            <span>
              <kbd className="font-mono bg-card px-1.5 py-0.5 rounded border border-border">↵</kbd> select
            </span>
          </div>

          {query.trim() && (
            <button
              onClick={handleSearchAll}
              className="text-xs font-bold text-foreground hover:underline inline-flex items-center gap-1"
            >
              <span>See all results in catalogue</span>
              <ArrowRight className="h-3 w-3" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
