"use client";

import { useState, useEffect, useRef } from "react";
import { Search } from "lucide-react";

interface AnimatedSearchBarProps {
  isAr: boolean;
  onSearch?: (query: string) => void;
  className?: string;
}

const ANIMATION_DURATION = 3000; // Time each placeholder is shown (ms)
const FADE_DURATION = 400; // Fade transition duration (ms)

const searchSuggestions = {
  en: [
    "Search patients, appointments...",
    "Find upcoming bookings...",
    "Search by patient name...",
    "Look up appointment history...",
    "Find available time slots...",
    "Search WhatsApp messages...",
  ],
  ar: [
    "البحث في المرضى، المواعيد...",
    "البحث عن الحجوزات القادمة...",
    "البحث باسم المريض...",
    "عرض سجل المواعيد...",
    "البحث عن المواعيد المتاحة...",
    "البحث في رسائل واتساب...",
  ],
};

export function AnimatedSearchBar({
  isAr,
  onSearch,
  className = "",
}: AnimatedSearchBarProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  const suggestions = isAr ? searchSuggestions.ar : searchSuggestions.en;

  useEffect(() => {
    // Don't animate if input is focused or has value
    if (isFocused || inputValue) return;

    const interval = setInterval(() => {
      setIsAnimating(true);

      setTimeout(() => {
        setCurrentIndex((prev) => (prev + 1) % suggestions.length);
        setIsAnimating(false);
      }, FADE_DURATION);
    }, ANIMATION_DURATION);

    return () => clearInterval(interval);
  }, [suggestions.length, isFocused, inputValue]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && inputValue.trim() && onSearch) {
      onSearch(inputValue.trim());
    }
  };

  return (
    <div className={`relative w-full group ${className}`}>
      {/* Hidden actual input */}
      <input
        ref={inputRef}
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        onKeyDown={handleKeyDown}
        className="w-full h-10 pl-10 pr-12 rounded-xl border border-slate-200 bg-slate-50/50 text-sm text-slate-800 transition-all focus:border-brand-green focus:bg-white focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
        aria-label={isAr ? "بحث" : "Search"}
      />

      {/* Animated placeholder overlay */}
      {!inputValue && !isFocused && (
        <div
          className="absolute inset-0 flex items-center pointer-events-none pl-10 pr-12"
          aria-hidden="true"
        >
          <span
            className={`text-sm text-slate-400 transition-all duration-300 ${
              isAnimating
                ? "opacity-0 translate-y-2"
                : "opacity-100 translate-y-0"
            }`}
          >
            {suggestions[currentIndex]}
          </span>
        </div>
      )}

      {/* Static placeholder when focused but empty */}
      {!inputValue && isFocused && (
        <div
          className="absolute inset-0 flex items-center pointer-events-none pl-10 pr-12"
          aria-hidden="true"
        >
          <span className="text-sm text-slate-300">
            {isAr ? "اكتب للبحث..." : "Type to search..."}
          </span>
        </div>
      )}

      {/* Search icon */}
      <Search
        className={`absolute top-1/2 -translate-y-1/2 w-4 h-4 transition-colors duration-200 ${
          isAr ? "right-3" : "left-3"
        } ${isFocused ? "text-brand-green" : "text-slate-400"}`}
      />

      {/* Keyboard shortcut */}
      <kbd
        className={`absolute top-1/2 -translate-y-1/2 hidden sm:inline-flex items-center gap-1 rounded border border-slate-200 bg-slate-100 px-1.5 py-0.5 text-xs text-slate-500 font-mono transition-opacity ${
          isAr ? "left-3" : "right-3"
        } ${isFocused || inputValue ? "opacity-0" : "opacity-100"}`}
      >
        ⌘K
      </kbd>
    </div>
  );
}

export default AnimatedSearchBar;
