"use client";

import { useState, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";

export default function VoiceSearch() {
  const [listening, setListening] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const recognitionRef = useRef<SpeechRecognition | null>(null);
  const router = useRouter();

  const isSupported =
    typeof window !== "undefined" &&
    (window.SpeechRecognition || window.webkitSpeechRecognition);

  const startListening = useCallback(() => {
    if (!isSupported) {
      setError("Your browser doesn't support voice search");
      setTimeout(() => setError(null), 3000);
      return;
    }

    const SpeechRecognitionAPI =
      window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SpeechRecognitionAPI) return;
    const recognition = new SpeechRecognitionAPI();
    recognition.lang = "en-US";
    recognition.interimResults = false;
    recognition.maxAlternatives = 1;

    recognition.onresult = (event: SpeechRecognitionEvent) => {
      const text = event.results[0][0].transcript;
      if (text.trim()) {
        router.push(`/search/results?keyword=${encodeURIComponent(text.trim())}`);
      }
      setListening(false);
    };

    recognition.onerror = () => {
      setListening(false);
      setError("Could not recognize speech. Try again.");
      setTimeout(() => setError(null), 3000);
    };

    recognition.onend = () => {
      setListening(false);
    };

    recognitionRef.current = recognition;
    recognition.start();
    setListening(true);
    setError(null);
  }, [isSupported, router]);

  const stopListening = useCallback(() => {
    recognitionRef.current?.stop();
    setListening(false);
  }, []);

  return (
    <div className="relative inline-flex items-center">
      <button
        type="button"
        onClick={listening ? stopListening : startListening}
        className={`w-10 h-10 rounded-full border-2 border-gold flex items-center justify-center transition-all duration-200 ${
          listening
            ? "bg-red-600/20 border-red-500"
            : "bg-surface hover:bg-surface-light"
        }`}
        title={listening ? "Stop listening" : "Voice search"}
        aria-label={listening ? "Stop voice search" : "Start voice search"}
      >
        {listening ? (
          <span className="relative flex h-3 w-3">
            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-500 opacity-75" />
            <span className="relative inline-flex h-3 w-3 rounded-full bg-red-500" />
          </span>
        ) : (
          <svg
            className="w-4 h-4 text-gold"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"
            />
          </svg>
        )}
      </button>

      {error && (
        <div className="absolute top-full mt-2 right-0 bg-surface border border-red-500/30 text-red-400 text-xs rounded-lg px-3 py-2 whitespace-nowrap z-10">
          {error}
        </div>
      )}
    </div>
  );
}
