import Input from "@/components/Forms/Input";
import { GetForm } from "@/utils";
import { useState } from "react";
import { toast } from "react-toastify";

const FormPagamento = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  ...rest
}: any) => {
  // const [anexo, setAnexo] = useState<File>();
  const [anexo, setAnexo] = useState<File>();
  const [arquivo_base64, setArquivo_base64] = useState<any>();
  const { handleSubmit, ...form } = GetForm();

  function onSubmitFormPagamento(data: any) {
    if (!arquivo_base64 || !anexo) {
      return toast.error("Informe o Comprovante");
    }
    const newData = { ...data, arquivo_base64, nome_arquivo: anexo.name };
    return onSubmitFunction(newData);
  }

  return (
    <form
      onSubmit={handleSubmit(onSubmitFormPagamento)}
      {...rest}
      className="flex flex-col gap-3"
    >
      <div className="flex flex-col gap-2">
        <Input
          name="anexo"
          label="Comprovante"
          type="file"
          formulario={form}
          // error={"Anexe o comprovante"}
          // required
          onInputProp={(event: any) => {
            const inputElement = event.target as HTMLInputElement;

            if (inputElement.files && inputElement.files.length > 0) {
              const file = inputElement.files[0];
              const reader = new FileReader();
              reader.onloadend = () => {
                const base64String = reader.result as string;

                setAnexo(file);
                setArquivo_base64(base64String);
              };

              reader.readAsDataURL(file);
            }
            return 1;
          }}
          onRemoveFile={() => {
            setAnexo(undefined), setArquivo_base64(null);
          }}
        />
        <Input
          label="Data Pagamento"
          name="dataPagamento_parcelamento"
          formulario={form}
          error="Informe a data de pagamento"
          type="date"
          required
          defaultValue={new Date().toISOString().split("T")[0]}
        />
      </div>
      {children}
    </form>
  );
};

export default FormPagamento;
