import LoadingWheel from '../LoadingWheel';
import { useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Plus } from 'lucide-react';
import { axiosClient } from '@/utils/axiosClient';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

type Inputs = {
  groupName: string;
};

function CreateGroupButton() {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [open, setOpen] = useState(false);

  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);
        setOpen(false);
      }
      reset();
    } catch (e) {
      console.error('Failed to create group: ', e);
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button
          className="p-2 hover:bg-zinc-800 rounded-lg"
          title="Create group"
        >
          <Plus />
        </button>
      </DialogTrigger>
      <DialogContent className="bg-zinc-950 text-white sm:max-w-md w-full">
        <DialogHeader>
          <DialogTitle className="text-center text-gray-200">
            Enter group name
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="p-3">
            <Input
              {...register('groupName', {
                required: true,
                minLength: 4,
                maxLength: 20,
              })}
              className="bg-gray-100 text-black h-10 rounded-lg"
              aria-invalid={errors.groupName ? 'true' : 'false'}
            />
            {errors.groupName?.type === 'minLength' && (
              <p className="text-sm text-gray-300">Group name is too short</p>
            )}
            {errors.groupName?.type === 'maxLength' && (
              <p className="text-sm text-red-300 ">Group name is too long</p>
            )}
          </div>
          <div className="flex justify-center">
            <Button
              type="submit"
              className="bg-green-500 text-black hover:bg-green-600"
              disabled={isLoading}
            >
              {isLoading ? <LoadingWheel /> : 'Create'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default CreateGroupButton;
