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

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

const attributeProductType = [
  { label: "عمومی", value: true },
  {
    label: "اختصاصی",
    value: false,
  },
];

const brokerRecieveWageTypes = [
  { label: "الزامی", value: true },
  {
    label: "اختیاری",
    value: false,
  },
];

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

  const [isGlobal, setIsGlobal] = useState(
    item?.broker_type === "exclusive" ? false : true
  );
  const [isRequired, setIsRequired] = useState(item ? item?.required : true);

  const schema = z.object({
    name: zValidateString("نام "),
    type: zValidateAutoComplete("نوع محاسبه"),
    organization_type: zValidateNumber("سازمان"),
    product: isGlobal
      ? zValidateAutoCompleteOptional()
      : zValidateAutoComplete("محصول"),
    fix_broker_price_state: z.boolean(),
    fix_broker_price: zValidateNumberOptional("تعرفه ثابت"),
  });

  type FormValues = z.infer<typeof schema>;

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

  const fixBrokerState = watch("fix_broker_price_state");

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data.name,
        ...(isGlobal ? { product: null } : { product: data?.product?.[0] }),
        organization_type: data.organization_type,
        calculation_strategy: data.type[0],
        broker_type: isGlobal ? "public" : "exclusive",
        required: isRequired,
        ...(fixBrokerState === true &&
        checkAccess({ page: "pricing", access: "Set-Broker-Fixed-Price" })
          ? { fix_broker_price: data?.fix_broker_price }
          : {}),
        ...(checkAccess({ page: "pricing", access: "Set-Broker-Fixed-Price" })
          ? { fix_broker_price_state: data?.fix_broker_price_state }
          : {}),
      });
      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="name"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام کارگزار "
              value={field.value}
              onChange={field.onChange}
              error={!!errors.name}
              helperText={errors.name?.message}
            />
          )}
        />
        <RadioGroup
          groupTitle="نوع کارگزار"
          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="organization_type"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.organization_type?.id}
              title="نهاد"
              api={`auth/api/v1/organization-type`}
              keyField="id"
              valueField="name"
              error={!!errors.organization_type}
              errorMessage={errors.organization_type?.message}
              onChange={(r) => {
                setValue("organization_type", r);
              }}
            />
          )}
        />

        <Controller
          name="type"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.calculation_strategy?.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]);
                }}
              />
            </>
          )}
        />

        <RadioGroup
          groupTitle="دریافت تعرفه"
          className="mr-2 mt-2"
          direction="row"
          options={brokerRecieveWageTypes}
          name="دریافت تعرفه"
          value={isRequired}
          onChange={(e) =>
            e.target.value === "true"
              ? setIsRequired(true)
              : setIsRequired(false)
          }
        />

        {checkAccess({ page: "pricing", access: "Set-Broker-Fixed-Price" }) && (
          <Controller
            name="fix_broker_price_state"
            control={control}
            render={({ field }) => (
              <Checkbox
                checked={field.value}
                onChange={field.onChange}
                label="تعرفه ثابت"
              />
            )}
          />
        )}

        {checkAccess({ page: "pricing", access: "Set-Broker-Fixed-Price" }) &&
          fixBrokerState === true && (
            <Controller
              name="fix_broker_price"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="تعرفه ثابت "
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.fix_broker_price}
                  helperText={errors.fix_broker_price?.message}
                />
              )}
            />
          )}

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