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

type AddPosProps = {
  getData: () => void;
  item?: any;
  deviceId: string;
};

export const PosAllocateOrganizationAccount = ({
  getData,
  item,
  deviceId,
}: AddPosProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();

  const schema = z.object({
    organization: zValidateAutoComplete("سازمان"),
  });

  type FormValues = z.infer<typeof schema>;

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

  const mutation = useApiMutation({
    api: `/pos_device/web/v1/pos/stake_holders/`,
    method: "post",
  });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        stakeholders: data?.organization?.map((opt: string | number) => {
          return {
            organization: opt,
            device: parseInt(deviceId),
            assignment: item?.assignment?.id,
          };
        }),
      });

      showToast(getToastResponse(item, ""), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast(
          error?.response?.data?.message || "این مورد تکراری است!",
          "error"
        );
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="organization"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.organization?.id}
                multiple
                title="انتخاب سازمان"
                api={`auth/api/v1/organization/organizations_by_province?exclude=PSP&province=${item?.organization?.province}`}
                keyField="id"
                valueField="name"
                error={!!errors.organization}
                errorMessage={errors.organization?.message}
                onChange={(r) => {
                  setValue("organization", r);
                }}
              />
            </>
          )}
        />

        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
