import LoadingWheel from '../LoadingWheel.tsx';
import { useRef, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Plus } from 'lucide-react';
import { axiosClient } from '@/utils/axiosClient.ts';

type Inputs = {
  groupName: string;
};

function CreateGroupButton() {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const modalRef = useRef<HTMLDialogElement | null>(null);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = async (data) => {
    try {
      setIsLoading(true);
      const response = await axiosClient.post(`/api/chat/groups/create`, data);
      console.log(response.data);
      if (response.data.group_id) {
        setIsLoading(false);
        if (modalRef.current) {
          modalRef.current.close();
        }
      }
      reset();
    } catch (e) {
      console.error('Failed to create group: ', e);
      setIsLoading(false);
    }
  };

  return (
    <>
      <div>
        <button
          className="p-2 hover:bg-zinc-800 rounded-lg"
          onClick={() =>
            (
              document.getElementById('createGroupModal') as HTMLDialogElement
            ).showModal()
          }
        >
          <Plus />
        </button>
        <dialog id="createGroupModal" className="modal" ref={modalRef}>
          <div className="modal-box bg-gray-800 text-center relative p-1">
            <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 group name</h3>
              <form
                onSubmit={handleSubmit(onSubmit)}
                className="w-full max-w-xs relative"
              >
                <input
                  className="input input-bordered bg-green-50 w-full h-10 text-black rounded-md text-center"
                  {...register('groupName', {
                    required: true,
                    minLength: 4,
                    maxLength: 20,
                  })}
                  aria-invalid={errors.groupName ? 'true' : 'false'}
                />
                {errors.groupName?.type === 'minLength' && (
                  <p className="text-gray-300">group name is too short</p>
                )}
                {errors.groupName?.type === 'maxLength' && (
                  <p className="text-gray-300">group name is too long</p>
                )}
              </form>
            </div>

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

export default CreateGroupButton;
