import LoadingWheel from '../LoadingWheel.tsx';
import { useEffect, useRef, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { socket } from '@/socket/socket.ts';
import { UserRoundPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { useChat } from '@/context/chat/useChat.ts';
import { axiosClient } from '@/utils/axiosClient.ts';
import axios from 'axios';

type Inputs = {
  username: string;
};

function AddGroupMember() {
  const { currentContact } = useChat();
  const { register, handleSubmit, watch, reset } = useForm<Inputs>();
  const modalRef = useRef<HTMLDialogElement | null>(null);
  const contactInput = watch('username');
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [notFound, setNotFound] = useState<boolean>(false);
  const [selectedIndex, setSelectedIndex] = useState<number>(0);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  useEffect(() => {
    const fetchSuggestions = async () => {
      if (contactInput?.length >= 3) {
        try {
          setIsLoading(true);
          setErrorMessage(null);
          const response = await axiosClient.get(
            `/api/chat/contacts/suggestions/${contactInput}`,
          );
          setSuggestions(response.data);
          setSelectedIndex(0);
          if (response.data.length < 1) {
            setIsLoading(false);
            setNotFound(true);
          } else {
            setIsLoading(false);
            setNotFound(false);
          }
        } catch (e) {
          if (axios.isAxiosError(e)) {
            setIsLoading(false);
            console.error('Error fetching suggestions:', e);
            setErrorMessage(
              e.response?.data?.message || 'Failed to fetch suggestions',
            );
          } else {
            console.error('Unexpected error occurred');
          }
        }
      } else {
        setNotFound(false);
        setIsLoading(false);
        setSuggestions([]);
      }
    };

    const delay = setTimeout(() => {
      fetchSuggestions();
    }, 300);

    return () => clearTimeout(delay);
  }, [contactInput]);

  if (!socket) return;

  const onSubmit: SubmitHandler<Inputs> = async (data) => {
    const contactToSubmit =
      suggestions.length > 0
        ? suggestions[selectedIndex]
        : data.username.trim();

    try {
      setIsLoading(true);
      setErrorMessage(null);
      const response = await axiosClient.post(`/api/chat/groups/addMember/`, {
        group_id: currentContact?.conversation_id,
        username: contactToSubmit,
      });
      console.log('Add member to group', response);
      setIsLoading(false);
      socket?.emit('added to group', {
        group_id: currentContact?.conversation_id,
      });
      if (modalRef.current) {
        modalRef.current.close();
      }
      reset();
    } catch (e) {
      if (axios.isAxiosError(e)) {
        console.error('Failed to add group member: ', e);
        setIsLoading(false);
        setErrorMessage(e.response?.data?.message || 'Failed to add member');
      } else {
        console.error('Unexpected error occurred');
      }
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (suggestions.length > 0) {
      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setSelectedIndex((prev) => (prev + 1) % suggestions.length);
          break;
        case 'ArrowUp':
          e.preventDefault();
          setSelectedIndex(
            (prev) => (prev - 1 + suggestions.length) % suggestions.length,
          );
          break;
        case 'Enter':
          if (suggestions.length > 0) {
            e.preventDefault();
            reset({ username: suggestions[selectedIndex] });
            handleSubmit(onSubmit)();
          }
          break;
      }
    }
  };

  return (
    <>
      <div>
        <button
          className="p-2 hover:bg-zinc-800 rounded-lg"
          onClick={() =>
            (
              document.getElementById('addMemberModal') as HTMLDialogElement
            ).showModal()
          }
        >
          <UserRoundPlus />
        </button>
        <dialog id="addMemberModal" className="modal" ref={modalRef}>
          <div className="modal-box bg-zinc-950 text-center relative p-1 border">
            <div className="absolute right-2 top-2">
              <form method="dialog">
                <button className=" btn btn-sm btn-circle btn-ghost">✕</button>
              </form>
            </div>

            <div className="flex flex-col items-center justify-center pb-1 mt-6">
              <h3 className="text-lg mb-4">Enter username</h3>
              <div className="text-center">
                <form onSubmit={handleSubmit(onSubmit)}>
                  <input
                    className="text-black bg-green-50 pl-2 shadow-lg rounded-md h-10 mb-2 mt-2"
                    type="text"
                    onKeyDown={handleKeyDown}
                    {...register('username', {
                      minLength: 4,
                      maxLength: 20,
                    })}
                  />
                </form>
                <div className="m-1">
                  {suggestions?.length > 0 ? (
                    <ul className="text-left p-2 bg-gray-900 shadow-md rounded-md w-full border">
                      {suggestions.map((suggestion, index) => (
                        <li
                          key={suggestion}
                          className={`p-1 cursor-pointer rounded-md mt-1 mb-1 ${
                            index === selectedIndex
                              ? 'bg-gray-500'
                              : 'hover:bg-gray-500'
                          }`}
                          onClick={() => {
                            handleSubmit(() =>
                              onSubmit({ username: suggestion }),
                            )();
                            setSuggestions([]);
                          }}
                        >
                          {suggestion}
                        </li>
                      ))}
                    </ul>
                  ) : isLoading ? (
                    <LoadingWheel />
                  ) : null}
                  {notFound ? (
                    <p className="p-1 bg-gray-800 shadow-md rounded-md w-full border text-gray-400">
                      user not found
                    </p>
                  ) : null}
                </div>
              </div>
              {errorMessage && (
                <p className="text-red-500 mt-2 p-1 bg-gray-800  rounded-md w-full">
                  {errorMessage}
                </p>
              )}
            </div>

            <div className="mt-4 flex justify-center">
              <Button
                type="submit"
                onClick={handleSubmit(onSubmit)}
                className="w-24 btn btn-sm bg-emerald-600 text-white hover:bg-green-500 border-black"
              >
                {isLoading ? <LoadingWheel /> : 'Add'}
              </Button>
            </div>
          </div>
        </dialog>
      </div>
    </>
  );
}

export default AddGroupMember;
