import { useState, useEffect, useRef } from 'react';
import { Search, X } from 'lucide-react';
import { supabase } from '../../lib/supabase';

const STATUS_COLORS = {
  'новая': '#8C9097', 'замер': '#F59E0B', 'согласование': '#8b5cf6',
  'монтаж': '#4361EE', 'закрыт': '#22C55E',
};

export function SearchModal({ onClose, onOpenOrder }) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const inputRef = useRef(null);
  const debounceRef = useRef(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  // Close on Escape
  useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [onClose]);

  const search = (q) => {
    clearTimeout(debounceRef.current);
    if (!q.trim()) { setResults([]); return; }
    debounceRef.current = setTimeout(async () => {
      setLoading(true);
      const { data } = await supabase
        .from('orders')
        .select('id, name, phone, status, final_cost, created_at')
        .or(`name.ilike.%${q}%,phone.ilike.%${q}%,address.ilike.%${q}%`)
        .order('created_at', { ascending: false })
        .limit(15);
      setResults(data ?? []);
      setLoading(false);
    }, 250);
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 2000,
        background: 'rgba(0,0,0,0.45)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        paddingTop: '80px', padding: '80px 16px 16px',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: '#fff', borderRadius: '16px',
          width: '100%', maxWidth: '560px',
          boxShadow: '0 16px 48px rgba(0,0,0,0.2)',
          overflow: 'hidden',
        }}
      >
        {/* Search input */}
        <div style={{ display: 'flex', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid #E9ECEF', gap: '12px' }}>
          <Search size={18} style={{ color: '#8C9097', flexShrink: 0 }} />
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => { setQuery(e.target.value); search(e.target.value); }}
            placeholder="Поиск по имени, телефону, адресу..."
            style={{
              flex: 1, border: 'none', outline: 'none',
              fontSize: '1rem', fontFamily: 'var(--font-body)',
              color: 'var(--text-main)',
            }}
          />
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#8C9097', padding: '2px' }}>
            <X size={18} />
          </button>
        </div>

        {/* Results */}
        <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
          {loading && (
            <div style={{ padding: '20px', textAlign: 'center', color: '#8C9097', fontSize: '0.85rem' }}>Поиск...</div>
          )}
          {!loading && query && results.length === 0 && (
            <div style={{ padding: '20px', textAlign: 'center', color: '#8C9097', fontSize: '0.85rem' }}>Ничего не найдено</div>
          )}
          {!loading && !query && (
            <div style={{ padding: '20px', textAlign: 'center', color: '#8C9097', fontSize: '0.85rem' }}>
              Начните вводить для поиска
            </div>
          )}
          {results.map((o) => {
            const color = STATUS_COLORS[o.status] || '#8C9097';
            return (
              <div
                key={o.id}
                onClick={() => { onOpenOrder(o); onClose(); }}
                style={{
                  padding: '12px 20px', display: 'flex', alignItems: 'center',
                  gap: '12px', cursor: 'pointer', borderBottom: '1px solid #F3F4F6',
                  transition: 'background 0.1s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = '#F5F7FA'}
                onMouseLeave={(e) => e.currentTarget.style.background = ''}
              >
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: '0.92rem', marginBottom: '2px' }}>{o.name}</div>
                  <div style={{ fontSize: '0.75rem', color: '#8C9097' }}>
                    {o.phone}
                    {o.final_cost ? ` · ${Number(o.final_cost).toLocaleString('ru-RU')} ₽` : ''}
                  </div>
                </div>
                <span style={{
                  background: color + '1A', color,
                  fontSize: '0.7rem', fontWeight: 700,
                  padding: '3px 8px', borderRadius: '10px',
                  textTransform: 'uppercase', letterSpacing: '0.3px', flexShrink: 0,
                }}>
                  {o.status}
                </span>
              </div>
            );
          })}
        </div>

        {/* Footer hint */}
        <div style={{ padding: '10px 20px', borderTop: '1px solid #F3F4F6', fontSize: '0.72rem', color: '#8C9097', display: 'flex', gap: '12px' }}>
          <span>↵ открыть</span>
          <span>Esc закрыть</span>
        </div>
      </div>
    </div>
  );
}
