'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';

type SearchResult = {
  id: string;
  type: string;
  title: string;
  subtitle: string;
  href: string;
  icon: string;
};

type Props = {
  label: string;
};

export function GlobalSearchButton({ label }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    window.addEventListener('keydown', onKeyDown);
    window.setTimeout(() => inputRef.current?.focus(), 0);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const trimmed = query.trim();
    if (trimmed.length < 2) {
      setResults([]);
      setIsLoading(false);
      return;
    }

    const controller = new AbortController();
    const timeout = window.setTimeout(async () => {
      try {
        setIsLoading(true);
        const response = await fetch(`/api/global-search?q=${encodeURIComponent(trimmed)}`, {
          signal: controller.signal,
          cache: 'no-store',
        });

        if (!response.ok) {
          setResults([]);
          return;
        }

        const payload = (await response.json()) as { results?: SearchResult[] };
        setResults(payload.results || []);
      } catch (error) {
        if ((error as Error).name !== 'AbortError') {
          setResults([]);
        }
      } finally {
        setIsLoading(false);
      }
    }, 180);

    return () => {
      controller.abort();
      window.clearTimeout(timeout);
    };
  }, [isOpen, query]);

  return (
    <>
      <button
        type="button"
        className="dashboard-icon-button"
        aria-label={label}
        onClick={() => setIsOpen(true)}
      >
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path
            d="M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12Zm0 0c3.3 0 6 2.7 6 6m-1.5 5.5L20 21"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </button>

      {isOpen ? (
        <div className="global-search-overlay" role="dialog" aria-modal="true" aria-label={label}>
          <button
            type="button"
            className="global-search-backdrop"
            aria-label="Close search"
            onClick={() => setIsOpen(false)}
          />
          <section className="global-search-panel">
            <div className="global-search-input-shell">
              <span className="material-symbols-outlined">search</span>
              <input
                ref={inputRef}
                type="search"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder="Search users, contacts, campaigns, logs..."
              />
              <button type="button" onClick={() => setIsOpen(false)}>
                <span className="material-symbols-outlined">close</span>
              </button>
            </div>

            <div className="global-search-results">
              {query.trim().length < 2 ? (
                <p>Type at least 2 characters to search across BizOne.</p>
              ) : isLoading ? (
                <p>Searching...</p>
              ) : results.length === 0 ? (
                <p>No matching records found.</p>
              ) : (
                results.map((result) => (
                  <Link
                    key={result.id}
                    href={result.href}
                    className="global-search-result"
                    onClick={() => setIsOpen(false)}
                  >
                    <span className="global-search-result-icon material-symbols-outlined">
                      {result.icon}
                    </span>
                    <span className="global-search-result-copy">
                      <strong>{result.title}</strong>
                      <small>{result.subtitle || result.type}</small>
                    </span>
                    <span className="global-search-result-type">{result.type}</span>
                  </Link>
                ))
              )}
            </div>
          </section>
        </div>
      ) : null}
    </>
  );
}
