import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "@/components/ui/use-toast";
import Axios from "@/lib/Axios";
import { useMutation } from "@tanstack/react-query";
import { AxiosResponse, AxiosError } from "axios"; // Import AxiosError
import { useForm } from "react-hook-form";

type Note = {
  note: string;
};

type ErrorResponse = {
  message: string;
  error: string;
  statusCode: number;
};

export default function SendNote({
  id,
  parent_id = null,
  refetch,
}: {
  id: number;
  parent_id?: number | null;
  refetch: any;
}) {
  const {
    register,
    handleSubmit,
    reset,
    formState: { isSubmitting, errors },
  } = useForm<Note>();

  const mutation = useMutation<
    AxiosResponse<any>,
    AxiosError<ErrorResponse>, // Specify the error type
    Note
  >({
    mutationFn: send,
    onError: (error) => {
      // Extract the error message from the API response
      const errorMessage =  "User lacks required permissions to add a note";
      toast({
        variant: "destructive",
        title: "Error",
        description: errorMessage,
      });
    },
    onSuccess: (data, variables, context) => {
      toast({
        variant: "default",
        title: "Success",
        description: "Note added",
      });
      reset();
      refetch();
    },
  });

  function onSubmit(data: Note) {
    mutation.mutate(data);
  }

  function send(data: Note) {
    const sendData = {
      note: data.note,
      customer: id,
      parent_note: parent_id,
    };

    return Axios.post("/customers/notes/", sendData);
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="text-xs w-full">
      <Textarea
        {...register("note", { required: "Cannot be empty" })}
        placeholder="Add a comment..."
        className="text-xs py-2"
      />
      <p className="mt-2">{errors?.note?.message}</p>
      <Button type="submit" className="mt-2" size="sm" disabled={isSubmitting}>
        Send
      </Button>
    </form>
  );
}