// import Lottie from "lottie-react";
// import RecordingAnimation from "@/assets/ui-Icons/recording.json";
// import { MicIcon } from "@/assets/svgs/Icons";
// import { useState } from "react";
// import { useLocale } from "next-intl";
// import toast from "react-hot-toast";
// import { useTranslations } from "use-intl";

// interface Props {
//   debouncedTerm: String;
//   setSearchTerm: (value: any) => void;
//   setDebouncedTerm: (value: any) => void;
// }

// const RecordingInput = ({
//   setSearchTerm,
//   setDebouncedTerm,
//   debouncedTerm,
// }: Props) => {
//   const [isRecording, setIsRecording] = useState(false);
//   const locale = useLocale();
//   const lang = locale === "ar" ? "ar-SA" : locale === "ku" ? "ku-IQ" : "en-US";
//   console.log("🚀 ~ lang:", lang)
//   const t = useTranslations();
//   //   // Voice Search Functionality
//   const handleVoiceSearch = () => {
//     const SpeechRecognition =
//       window.SpeechRecognition || window.webkitSpeechRecognition;
//     // Check if the browser supports SpeechRecognition
//     if (!SpeechRecognition) {
//       toast.error(t("Messages.voice_not_supported"));
//       return;
//     }

//     const recognition = new SpeechRecognition();
//     recognition.lang = lang;
//     recognition.continuous = false;
//     recognition.interimResults = false;
//     recognition.maxAlternatives = 1;

//     // Start recording when the recognition starts
//     recognition.onstart = () => {
//       setIsRecording(true);
//     };

//     recognition.onerror = (event: any) => {
//       setIsRecording(false);
//       switch (event.error) {
//         case "no-speech":
//           toast.error(
//             t("Messages.no_speech_detected") ||
//               "No speech detected, please speak louder."
//           );
//           break;
//         case "audio-capture":
//           toast.error(
//             t("Messages.microphone_not_found") ||
//               "Microphone not found. Please check your audio device."
//           );
//           break;
//         case "not-allowed":
//           toast.error(
//             t("Messages.permission_denied") ||
//               "Microphone access denied. Please allow permission."
//           );
//           break;
//         default:
//           toast.error(
//             t("Messages.voice_not_supported") ||
//               "Voice recognition error occurred."
//           );
//           break;
//       }
//     };

//     recognition.onend = () => {
//       setIsRecording(false);
//     };

//     // Handle the result from speech recognition
//     recognition.onresult = (event: any) => {
//       console.log("🚀 ~ handleVoiceSearch ~ event:", event);
//       const voiceQuery = event.results[0][0].transcript;
//       setSearchTerm(voiceQuery);
//       setDebouncedTerm(voiceQuery.trim());
//       setIsRecording(false);
//     };

//     // Request microphone access and start recognition
//     navigator.mediaDevices
//       .getUserMedia({ audio: true })
//       .then(() => {
//         recognition.start();
//       })
//       .catch((error) => {
//         console.error("Microphone permission error:", error);
//         toast.error(t("Messages.allow_voice"));
//       });
//   };

//   const stopRecording = () => {
//     const SpeechRecognition =
//       window.SpeechRecognition || window.webkitSpeechRecognition;

//     if (!SpeechRecognition) {
//       toast.error(t("Messages.voice_not_supported"));
//       return;
//     }

//     const recognition = new SpeechRecognition();

//     if (recognition) {
//       recognition.stop();
//       setIsRecording(false);
//       setSearchTerm(debouncedTerm);
//       // toast.success("Recording stopped.");
//     }
//   };

//   return (
//     <div className="z-10 cursor-pointer bg-secColor rounded-full p-1.5">
//       {isRecording ? (
//         <Lottie
//           onClick={stopRecording}
//           className="size-8"
//           animationData={RecordingAnimation}
//         />
//       ) : (
//         <MicIcon onClick={handleVoiceSearch} className="size-6" />
//       )}
//     </div>
//   );
// };

import Lottie from "lottie-react";
import RecordingAnimation from "@/assets/ui-Icons/recording.json";
import { MicIcon } from "@/assets/svgs/Icons";
import { useState, useEffect } from "react";
import { useLocale } from "next-intl";
import toast from "react-hot-toast";
import { useTranslations } from "use-intl";
import SpeechRecognition, { useSpeechRecognition } from "react-speech-recognition";

interface Props {
  debouncedTerm: string;
  setSearchTerm: (value: any) => void;
  setDebouncedTerm: (value: any) => void;
}

const RecordingInput = ({ setSearchTerm, setDebouncedTerm, debouncedTerm }: Props) => {
  const [isRecording, setIsRecording] = useState(false);
  const [hasMicrophoneAccess, setHasMicrophoneAccess] = useState<boolean | null>(null);
  const [isFeatureSupported, setIsFeatureSupported] = useState<boolean>(true);
  const locale = useLocale();
  const t = useTranslations();

  // Language mapping
  const getLanguageCode = (locale: string) => {
    switch (locale) {
      case "ar":
        return "ar-SA"; 
      case "ku":
        return "ku";
      case "en":
      default:
        return "en-US";
    }
  };

  const {transcript, listening, resetTranscript, browserSupportsSpeechRecognition} = useSpeechRecognition();

  // Check feature support and microphone access on component mount
  useEffect(() => {
    const checkFeatureSupport = async () => {
      // Check if browser supports speech recognition
      if (!browserSupportsSpeechRecognition) {
        setIsFeatureSupported(false);
        return;
      }

      // Check if getUserMedia is available
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        setIsFeatureSupported(false);
        return;
      }

      // Check microphone access
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        setHasMicrophoneAccess(true);
        setIsFeatureSupported(true);
        
        // Stop the stream immediately as we only wanted to check permissions
        stream.getTracks().forEach(track => track.stop());
        
      } catch (error: any) {
        console.warn('Microphone access check failed:', error);
        
        if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
          setHasMicrophoneAccess(false);
          setIsFeatureSupported(true); // Feature exists but permission denied
        } else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
          setHasMicrophoneAccess(false);
          setIsFeatureSupported(false); // No microphone device found
        } else {
          setHasMicrophoneAccess(false);
          setIsFeatureSupported(false); // Other errors - assume unsupported
        }
      }
    };
    
    checkFeatureSupport();
  }, [browserSupportsSpeechRecognition]);

  useEffect(() => {
    if (transcript && !listening) {
      setSearchTerm(transcript);
      setDebouncedTerm(transcript.trim());
      resetTranscript();
    }
  }, [transcript, listening, setSearchTerm, setDebouncedTerm, resetTranscript]);

  useEffect(() => {
    setIsRecording(listening);
  }, [listening]);

  const handleVoiceSearch = async () => {
    // Check if feature is supported first
    if (!isFeatureSupported) {
      toast.error(t("Messages.device_not_supported") || "Your device does not support this feature");
      return;
    }

    if (!browserSupportsSpeechRecognition) {
      toast.error(t("Messages.voice_not_supported") || "Your device does not support this feature");
      return;
    }

    // Check if microphone access was denied
    if (hasMicrophoneAccess === false) {
      toast.error(t("Messages.permission_denied") || "Microphone access denied. Please allow permission.");
      return;
    }

    try {
      await navigator.mediaDevices.getUserMedia({ audio: true });
      
      resetTranscript();
      
      const recognition = new ((window as any).SpeechRecognition || (window as any).webkitSpeechRecognition)();
      
      recognition.lang = getLanguageCode(locale);
      recognition.continuous = false;
      recognition.interimResults = false;
      recognition.maxAlternatives = 1;

      recognition.onstart = () => {
        setIsRecording(true);
      };

      recognition.onerror = (event: any) => {
        setIsRecording(false);
        switch (event.error) {
          case "no-speech":
            toast.error(t("Messages.no_speech_detected") || "No speech detected, please speak louder.");
            break;
          case "audio-capture":
            toast.error(t("Messages.microphone_not_found") || "Microphone not found. Please check your audio device.");
            break;
          case "not-allowed":
            toast.error(t("Messages.permission_denied") || "Microphone access denied. Please allow permission.");
            break;
          case "network":
            toast.error(t("Messages.network_error") || "Network error occurred. Please check your connection.");
            break;
          case "service-not-allowed":
            toast.error(t("Messages.service_not_allowed") || "Speech recognition service not allowed.");
            break;
          default:
            toast.error(t("Messages.device_not_supported") || "Your device does not support this feature");
            break;
        }
      };

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

      recognition.onresult = (event: any) => {
        const voiceQuery = event.results[0][0].transcript;
        setSearchTerm(voiceQuery);
        setDebouncedTerm(voiceQuery.trim());
        setIsRecording(false);
      };

      recognition.start();
      
    } catch (error: any) {
      console.error("Microphone permission error:", error);
      
      if (error.name === 'NotAllowedError') {
        toast.error(t("Messages.permission_denied") || "Microphone access denied. Please allow permission.");
      } else if (error.name === 'NotFoundError') {
        toast.error(t("Messages.microphone_not_found") || "Microphone not found. Please check your audio device.");
      } else {
        toast.error(t("Messages.device_not_supported") || "Your device does not support this feature");
      }
    }
  };

  const stopRecording = () => {
    if (!browserSupportsSpeechRecognition) {
      toast.error(t("Messages.device_not_supported") || "Your device does not support this feature");
      return;
    }

    SpeechRecognition.stopListening();
    
    // If we have a transcript, use it; otherwise, keep the previous search term
    if (transcript) {
      setSearchTerm(transcript);
      setDebouncedTerm(transcript.trim());
    } else {
      setSearchTerm(debouncedTerm);
    }
    
    resetTranscript();
  };

  return (
    <div className="z-10 cursor-pointer bg-secColor rounded-full p-1.5">
      {isRecording ? (
        <Lottie 
          onClick={stopRecording} 
          className="size-8" 
          animationData={RecordingAnimation} 
        />
      ) : (
        <MicIcon 
          onClick={handleVoiceSearch} 
          className="size-6" 
        />
      )}
    </div>
  );
};

export default RecordingInput;