import React, { useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Calendar } from 'lucide-react';
import { DayPicker } from 'react-day-picker';
import { format } from 'date-fns';
import 'react-day-picker/dist/style.css';
import { ru } from 'date-fns/locale';


export function SearchBar() {
  const [searchQuery, setSearchQuery] = useState('');
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [selectedDate, setSelectedDate] = useState<Date>();
  const datePickerRef = useRef<HTMLDivElement>(null);

  const navigate = useNavigate();

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    if (searchQuery.trim()) {
      navigate(`/search?q=${encodeURIComponent(searchQuery.trim())}`);
    }
  };

  const handleSearchKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch(e);
    }
  };

  const handleDateSelect = (date: Date | undefined) => {
    setSelectedDate(date);
    setShowDatePicker(false);

    if (date) {
      const params = new URLSearchParams();
      params.set('date', format(date, 'yyyy-MM-dd'));
      if (searchQuery.trim()) {
        params.set('q', searchQuery.trim());
      }
      navigate(`/search?${params.toString()}`);
    }
  };

  // Close datepicker when clicking outside
  React.useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (datePickerRef.current && !datePickerRef.current.contains(event.target as Node)) {
        setShowDatePicker(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
      <form onSubmit={handleSearch} className="relative flex items-center space-x-2">
        {/* Обёртка для поля ввода и иконки поиска */}
        <div className="relative">
          <input
              type="text"
              placeholder="Поиск..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyDown={handleSearchKeyPress}
              className="w-40 lg:w-60 pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <button
              type="submit"
              className="absolute left-3 top-2.5 text-gray-400 hover:text-gray-600"
          >
            <Search size={18} />
          </button>
        </div>

        {/* Кнопка календаря */}
        <div className="relative">
          <button
              type="button"
              onClick={() => setShowDatePicker(!showDatePicker)}
              className={`px-3 py-2 border border-gray-300 rounded-full text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                  selectedDate ? 'bg-blue-50' : 'bg-white'
              }`}
          >
            <Calendar size={18} />
          </button>

          {showDatePicker && (
              <div
                  ref={datePickerRef}
                  className="absolute right-0 mt-2 bg-white rounded-lg shadow-lg z-50 border border-gray-200"
              >
                <DayPicker
                    mode="single"
                    selected={selectedDate}
                    onSelect={handleDateSelect}
                    locale={ru}
                    className="p-3"
                />
              </div>
          )}
        </div>

        {/* Показ выбранной даты */}
        {selectedDate && (
            <div className="text-sm text-gray-600 ml-2">
              {format(selectedDate, 'dd.MM.yyyy')}
            </div>
        )}
      </form>
  );
}