'use client';

import { useEffect, useRef, useState } from 'react';

import { useTranslations } from 'next-intl';

import { IoClose } from 'react-icons/io5';
import { PiMagnifyingGlass } from 'react-icons/pi';

import { cn } from '@/lib/utils';
import { getSearchUrl } from '@/utils/generalUtils';

import { useRouter } from '@/i18n/navigation';

interface SearchBarProps {
  closeMenu?: () => void;
  inputClassName?: string;
  isMobile?: boolean;
}

const SearchBar: React.FC<SearchBarProps> = ({ closeMenu, inputClassName, isMobile = false }) => {
  const [term, setTerm] = useState<string>('');
  const [isExpanded, setIsExpanded] = useState<boolean>(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const t = useTranslations('common');

  const router = useRouter();

  const search = () => {
    if (term.trim() !== '') {
      router.push(getSearchUrl(term) as never);
      setIsExpanded(false);

      if (closeMenu) {
        closeMenu();
      }
    }
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsExpanded(false);
      }
    };

    if (isExpanded) {
      document.addEventListener('mousedown', handleClickOutside);
    }

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

  // Focus input when expanded
  useEffect(() => {
    if (isExpanded && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isExpanded]);

  // Mobile mode - always show full input
  if (isMobile) {
    return (
      <div className="relative w-full">
        <input
          name={t('search')}
          ref={inputRef}
          type="text"
          placeholder={t('searchPlaceholder')}
          className={cn(
            'w-full font-roboto text-[#151720] bg-[#f4f3ef] border border-[#151720]/15 pl-3 pr-10 py-1.5 md:py-2 text-base shadow-sm focus:outline-none focus:ring-2 focus:ring-black/20',
            inputClassName
          )}
          value={term}
          onChange={(e) => setTerm(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') search();
            if (e.key === 'Escape') setTerm('');
          }}
        />

        {term && (
          <button
            type="button"
            aria-label={t('close')}
            onClick={() => {
              setTerm('');
              inputRef.current?.focus();
            }}
            className="absolute right-9 top-1/2 -translate-y-1/2 p-1"
          >
            <IoClose size={16} className="text-[#151720]/60 hover:text-[#151720]" />
          </button>
        )}

        <button
          type="button"
          aria-label={t('search')}
          onClick={() => search()}
          className="absolute right-2 top-1/2 transform -translate-y-1/2 transition-colors"
        >
          <PiMagnifyingGlass size={20} className="text-[#151720]/70 hover:text-[#151720]" />
        </button>
      </div>
    );
  }

  // Desktop mode
  return (
    <div className="relative" ref={containerRef}>
      {/* Icon button for lg-xl (1024-1280px) */}
      <button
        type="button"
        aria-label={t('searchOpen')}
        onClick={() => setIsExpanded(!isExpanded)}
        className={cn(
          'lg:flex 2xl:hidden px-2 md:px-4 shadow-sm transition-colors py-1.5 md:py-2 border border-[#151720]/20',
          isExpanded ? 'bg-[#151720] text-white' : 'bg-[#f4f3ef] text-[#151720] hover:bg-[#ece9e2]'
        )}
      >
        <PiMagnifyingGlass size={20} className="lg:w-6 lg:h-6" />
      </button>

      {/* Dropdown search input for lg-2xl when expanded */}
      {isExpanded && (
        <div className="absolute top-full right-0 mt-1 w-[280px] bg-white shadow-sm p-2 z-50 lg:block 2xl:hidden">
          <div className="relative">
            <input
              ref={inputRef}
              type="text"
              placeholder={t('searchPlaceholder')}
              className="w-full font-roboto text-[#151720] bg-[#f4f3ef] border border-[#151720]/15 pl-3 pr-10 py-1.5 md:py-2 text-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-black/20"
              value={term}
              onChange={(e) => setTerm(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') search();
                if (e.key === 'Escape') {
                  setTerm('');
                  setIsExpanded(false);
                }
              }}
            />

            {term && (
              <button
                type="button"
                aria-label={t('close')}
                onClick={() => {
                  setTerm('');
                  inputRef.current?.focus();
                }}
                className="absolute right-9 top-1/2 -translate-y-1/2 p-1"
              >
                <IoClose size={16} className="text-[#151720]/60 hover:text-[#151720]" />
              </button>
            )}

            <button
              type="button"
              aria-label={t('search')}
              onClick={() => search()}
              className="absolute right-2 top-1/2 transform -translate-y-1/2 transition-colors"
            >
              <PiMagnifyingGlass size={20} className="text-[#151720]/70 hover:text-[#151720]" />
            </button>
          </div>
        </div>
      )}

      {/* Full input bar for 2xl+ */}
      <div className="relative w-full min-w-[200px] hidden 2xl:block">
        <input
          name={t('search')}
          ref={inputRef}
          type="text"
          placeholder={t('searchPlaceholder')}
          className={cn(
            'w-full font-roboto text-[#151720] bg-[#f4f3ef] pl-3 pr-10 py-1.5 md:py-2 text-base shadow-sm focus:outline-none focus:ring-2 focus:ring-black/20 border border-[#151720]/20',
            inputClassName
          )}
          value={term}
          onChange={(e) => setTerm(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') search();
            if (e.key === 'Escape') setTerm('');
          }}
        />

        {term && (
          <button
            type="button"
            aria-label={t('close')}
            onClick={() => {
              setTerm('');
              inputRef.current?.focus();
            }}
            className="absolute right-9 top-1/2 -translate-y-1/2 p-1"
          >
            <IoClose size={16} className="text-[#151720]/60 hover:text-[#151720]" />
          </button>
        )}

        <button
          type="button"
          aria-label={t('search')}
          onClick={() => search()}
          className="absolute right-2 top-1/2 transform -translate-y-1/2 transition-colors"
        >
          <PiMagnifyingGlass size={20} className="text-[#151720]/70 hover:text-[#151720]" />
        </button>
      </div>
    </div>
  );
};

export default SearchBar;
