import { FormBuilder } from "@/components/FormBuilder";
import { FormCard, FormContent } from "@/components/FormCard";
import { Form } from "@/components/ui/form";
import { useGlobal } from "@/context/global";
import { ServerRequest } from "@/lib/actions";
import getAddDownloadLinkFields from "@/models/files/_getAddDownloadLinkFields";
import {
  AddDownloadLinkSchema,
  getAddDownloadLinkSchema,
} from "@/schemas/files/_addDownloadLink";
import { createDownloadLink } from "@/services/download/createlink";
import { socket } from "@/socket";
import { faCloudUpload } from "@fortawesome/free-solid-svg-icons";
import { zodResolver } from "@hookform/resolvers/zod";
import dayjs from "dayjs";
import { useSession } from "next-auth/react";
import { useTransition } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";

export function AddDownloadLinkForm({}) {
  const { dict, closeModal } = useGlobal();
  const { data: SessionData }: any = useSession();

  const [isPending, startTransition] = useTransition();

  const form = useForm<AddDownloadLinkSchema>({
    resolver: zodResolver(getAddDownloadLinkSchema(dict)),
    mode: "onChange",
    defaultValues: {
      title: "",
      file: [],
    },
  });

  const onChangeFile = (e: any) => {
    const target = e.target as HTMLInputElement;
    if (!target.files || target.files.length === 0) return;
    form.setValue("file", [target.files[0]]);
  };

  const onSubmit = (data: any) => {
    startTransition(() => {
      const promise = new Promise(async (resolve, reject) => {
        const formData = new FormData();

        formData.append("user", SessionData.user.id);
        formData.append("title", data.title);
        formData.append("file", data.file[0], data.file[0].name);

        const result = await ServerRequest(createDownloadLink(formData));

        if (!result.operation) {
          return reject(result);
        }

        socket.emit("add-download-link", result.data);

        form.reset();

        return resolve(result);
      });

      toast.promise(promise, {
        loading: dict.alerts.create_download_link.loading,
        description: dayjs().format("DD/MM/YYYY HH:mm"),
        success: ({ message }) => message,
        error: ({ message }) => message,
      });
    });
  };

  return (
    <FormCard>
      <FormContent title="New link" icon={faCloudUpload}>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormBuilder
              form={form}
              elements={getAddDownloadLinkFields({
                isPending,
                closeModal,
                dict,
              })}
              fileChange={onChangeFile}
              upperLabel
            />
          </form>
        </Form>
      </FormContent>
    </FormCard>
  );
}
