import { useState } from 'react';
import { Search } from 'lucide-react';
import { useSearchXmemMutation } from '../../store';

export function SearchBox() {
  const [query, setQuery] = useState('');
  const [search, { data, isLoading, error, reset }] = useSearchXmemMutation();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const q = query.trim();
    if (!q) return;
    await search({ query: q, limit: 10 });
  }

  function clear() {
    setQuery('');
    reset();
  }

  return (
    <div className="glass-light rounded-xl p-4">
      <h3 className="text-xs font-medium text-surface-400 uppercase tracking-wider mb-3 flex items-center gap-2">
        <Search className="w-4 h-4 text-cyan-400" />
        Ask the Team Memory
      </h3>

      <form onSubmit={handleSubmit} className="flex items-center gap-2">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder='e.g. "what is bob working on?"'
          className="flex-1 px-3 py-2 rounded-lg bg-surface-800/50 border border-surface-700 text-sm text-surface-100 placeholder:text-surface-500 focus:border-cyan-500 focus:outline-none"
        />
        <button
          type="submit"
          disabled={isLoading || !query.trim()}
          className="px-3 py-2 rounded-lg bg-cyan-500/20 border border-cyan-500/40 text-sm text-cyan-300 hover:bg-cyan-500/30 disabled:opacity-50"
        >
          {isLoading ? '…' : 'Search'}
        </button>
        {(data || error) && (
          <button
            type="button"
            onClick={clear}
            className="px-3 py-2 rounded-lg bg-surface-800/50 border border-surface-700 text-sm text-surface-400 hover:bg-surface-700/50"
          >
            Clear
          </button>
        )}
      </form>

      {error && (
        <p className="text-sm text-red-400 mt-3">
          Search failed: {(error as { data?: { error?: string } })?.data?.error ?? 'unknown error'}
        </p>
      )}

      {data && (
        <div className="mt-3 space-y-2 max-h-[300px] overflow-y-auto">
          <p className="text-xs text-surface-500">
            {data.count} result{data.count === 1 ? '' : 's'} for "{data.query}"
          </p>
          {data.results.map((r) => (
            <div
              key={r.eventId}
              className="p-2 rounded-lg bg-surface-800/50 border border-surface-700"
            >
              <div className="flex items-center gap-2 mb-1">
                <span className="text-xs font-mono uppercase text-cyan-400">
                  {r.eventType.replace('_', ' ')}
                </span>
                <span className="text-xs text-surface-500 ml-auto font-mono">
                  {new Date(r.timestamp).toLocaleString()}
                </span>
              </div>
              <p className="text-sm text-surface-200">{r.summary}</p>
              <p className="text-xs text-surface-500 mt-1 font-mono">{r.agentId}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
