import { createSignal } from "solid-js";
import { FormGroup } from "@components/FormGroup";
import Toast from "@utils/toast";

type Chat = {
  name: string;
  subject: string;
  id: number;
  slug: string;
};

export const ReplyForm = ({ id, name, slug }: Partial<Chat>) => {
  const [loading, setLoading] = createSignal(false);
  const [message, setMessage] = createSignal<string>();
  let reply_form;
  const send = async (form: SubmitEvent) => {
    form.preventDefault();
    setLoading(true);

    const response = await fetch("/api/chat/reply", {
      method: "POST",
      body: new FormData(form.target as HTMLFormElement),
    });

    const json = await response.json();
    console.log({ json });
    if (response.ok) {
      // @ts-ignore
      reply_form.reset();
      await Toast.fire({
        title: "Sent",
        html: `
        <strong> You just replied "${name ?? ""}"</strong> 
        `,
      });

      return window.location.assign(`/dashboard/messages/${slug}-msg-${id}`);
    } else
      await Toast.fire({
        title: "Try Again",
      });
    setLoading(false);
  };
  return (
    <>
      <form
        method="post"
        onSubmit={(form) => send(form)}
        ref={(e) => (reply_form = e)}
        class="flex flex-col gap-3"
      >
        <div class="flex flex-wrap gap-3">
          <FormGroup name="id" hidden={true} value={id} className="grow" />
          <div class="flex flex-col gap-1 w-full">
            <label for="message" class="px-2">
              <small>Send A Reply</small>
            </label>
            <textarea
              class="min-h-[10rem] p-3 rounded-lg border border-blue-900/5 outline-0 max-w-full"
              name="message"
              required={true}
              placeholder={"Type your message"}
              value={message() ?? ""}
              onchange={(e) => setMessage(e.target.value)}
            />
          </div>
        </div>
        <div class="flex flex-wrap justify-center sm:justify-end gap-3">
          <button
            type="reset"
            class="border-blue-950 border rounded-lg text-blue-950 p-2 w-[10rem]"
          >
            Clear
          </button>
          <button
            type="submit"
            class="bg-blue-950 rounded-lg text-white p-2 w-[10rem]"
          >
            {loading() ? "...loading" : "Reply"}
          </button>
        </div>
      </form>
    </>
  );
};
