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

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

const attributeProductType = [
  { label: "عمومی", value: true },
  {
    label: "به ازای محصول",
    value: false,
  },
];

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

  const [isGlobal, setIsGlobal] = useState(item ? item?.is_global : true);

  const schema = z.object({
    name: zValidateString("نام "),
    type: zValidateAutoComplete("نوع مولفه"),
    product: isGlobal
      ? zValidateAutoCompleteOptional()
      : zValidateAutoComplete("محصول"),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: item?.name || "",
      type: item?.type ? [item?.type] : [],
      product: item?.type.id ? [`${item?.type.id}`] : [],
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data?.name,
        type: data?.type[0],
        is_global: isGlobal,
        ...(isGlobal ? { product: null } : { product: data?.product?.[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">
        <RadioGroup
          className="mr-2 mt-2"
          direction="row"
          options={attributeProductType}
          name="نوع مولفه"
          value={isGlobal}
          onChange={(e) =>
            e.target.value === "true" ? setIsGlobal(true) : setIsGlobal(false)
          }
        />

        {!isGlobal && (
          <Controller
            name="product"
            control={control}
            render={() => (
              <>
                <FormApiBasedAutoComplete
                  defaultKey={item?.product?.id}
                  title="انتخاب محصول"
                  api={`product/web/api/v1/product`}
                  keyField="id"
                  valueField="name"
                  error={!!errors.product}
                  errorMessage={errors.product?.message}
                  onChange={(r) => {
                    setValue("product", [r]);
                  }}
                />
              </>
            )}
          />
        )}

        <Controller
          name="name"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام مولفه "
              value={field.value}
              onChange={field.onChange}
              error={!!errors.name}
              helperText={errors.name?.message}
            />
          )}
        />

        <Controller
          name="product"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.type?.id}
                title="نوع مولفه"
                api={`product/web/api/v1/sale_unit`}
                keyField="id"
                valueField="unit"
                error={!!errors.type}
                errorMessage={errors.type?.message}
                onChange={(r) => {
                  setValue("type", [r]);
                }}
              />
            </>
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
