import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { getDateBrasil, GetForm } from "@/utils";
import { useState } from "react";

export default function ContatoCliente({ onSubmitFunction }: any) {
  const [feedback, setFeedback] = useState();
  const [isLoading, setIsLoading] = useState(false);

  const { handleSubmit, ...form } = GetForm();

  async function salvarContatoCliente(data: any) {
    if (
      data?.dataFutura &&
      !(new Date(data?.dataFutura) > new Date(data?.dataContato_cliente_coleta))
    ) {
      form?.setError("dataFutura", {
        type: "manual",
        message: "Data futura precisa ser superior a data do contato",
      });
      return;
    }
    setIsLoading(true);
    return onSubmitFunction(data).finally(() => setIsLoading(false));
  }

  return (
    <div className="flex flex-col gap-4" key={form?.key}>
      <div className="flex flex-row gap-4">
        <Input
          name="dataContato_cliente_coleta"
          label="Data"
          formulario={form}
          type="date"
          width="w-fit"
          required
          error="Informe a data que ocorreu"
          defaultValue={getDateBrasil(undefined, undefined, "fr-CA")}
        />
        <InputSelectComponent
          name="feedback"
          label="Feedback do Cliente"
          formulario={form}
          options={[
            {
              label: "Gerar Proposta",
              value: "1",
            },
            {
              label: "Contato Futuro",
              value: "2",
            },
            {
              label: "Cliente não quer",
              value: "3",
            },
          ]}
          onChange={(e: any) => {
            setFeedback(e?.value);
            if (e?.value != "2") {
              form?.unregister(["dataFutura"] as never[], {
                keepValue: false,
                keepError: false,
              });
              form.reload();
            }
          }}
          width="min-w-[250px]"
          required
          error="Informe o Feedback"
        />
        {feedback == "2" && (
          <Input
            name="dataFutura"
            label="Data para Contato"
            formulario={form}
            type="date"
            width="w-fit"
            required
            error="Informe a data para contato futuro"
            onChange={() => {
              form?.clearErrors("dataFutura");
            }}
          />
        )}
      </div>

      <Input
        name="obsContato_cliente_coleta"
        label="Observações Gerais"
        formulario={form}
        type="textarea"
      />
      <div className="flex flex-row-reverse w-full">
        <Button
          loading={isLoading}
          onClick={handleSubmit(salvarContatoCliente)}
        >
          Salvar
        </Button>
      </div>
    </div>
  );
}
