import { Controller, useForm } from "react-hook-form";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import { useModalStore } from "../../context/zustand-store/appStore";
import { zValidateAutoComplete } from "../../data/getFormTypeErrors";
import { useToast } from "../../hooks/useToast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useApiMutation } from "../../utils/useApiRequest";
import { getToastResponse } from "../../data/getToastResponse";
import { z } from "zod";
import Button from "../../components/Button/Button";
import { Grid } from "../../components/Grid/Grid";

type Props = {
  getData: () => void;
  item?: any;
};

export const AllocateAccountToBroker = ({ getData, item }: Props) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();

  const schema = z.object({
    broker: zValidateAutoComplete("کارگزار "),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      broker: item?.broker?.id ? [item?.broker?.id] : [],
    },
  });

  const mutation = useApiMutation({
    api: `/pos_device/web/v1/pos/stake_holders/${item ? item?.id + "/" : ""}`,
    method: "put",
  });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        assignment: item?.assignment,
        device: item?.device_id,
        organization: item?.organization?.id,
        broker: data?.broker[0],
      });
      showToast(getToastResponse(item, "کارگزار"), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast("این مولفه تکراری است!", "error");
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2 justify-center">
        <Controller
          name="broker"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.broker?.id}
                title="کارگزار"
                api={`product/web/api/v1/broker`}
                keyField="id"
                valueField="name"
                error={!!errors.broker}
                errorMessage={errors.broker?.message}
                onChange={(r) => {
                  setValue("broker", [r]);
                }}
              />
            </>
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
