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,
  zValidateNumber,
  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 AutoComplete from "../../components/AutoComplete/AutoComplete";
import { ImageUploader } from "../../components/ImageUploader/ImageUploader";
import { useState } from "react";

const schema = z.object({
  name: zValidateString("نام "),
  category: zValidateNumber("دسته بندی"),
  type: zValidateAutoComplete("نوع محصول"),
});

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

type FormValues = z.infer<typeof schema>;

const productTypes = [
  { key: "gov", value: "دولتی", disabled: false },
  { key: "free", value: "آزاد", disabled: false },
];

export const AddProduct = ({ getData, item }: AddPageProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const [image, setImage] = useState<string>("");

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

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data?.name,
        type: data?.type[0],
        category: data?.category,
        image: image || undefined,
      });
      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}
            />
          )}
        />

        <Controller
          name="category"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                selectField
                defaultKey={item?.category?.id}
                title="دسته بندی"
                api={`product/web/api/v1/category`}
                keyField="id"
                valueField="name"
                error={!!errors.category}
                errorMessage={errors.category?.message}
                onChange={(r) => {
                  setValue("category", r);
                }}
              />
            </>
          )}
        />

        <Controller
          name="type"
          control={control}
          render={({ field }) => (
            <AutoComplete
              selectField
              data={productTypes}
              selectedKeys={field.value}
              onChange={(keys: (string | number)[]) => {
                setValue("type", keys);
              }}
              error={!!errors.type}
              helperText={errors.type?.message}
              title="نوع محصول"
            />
          )}
        />

        <ImageUploader
          maxSize={1024 * 1024}
          onImageSelected={(base64) => setImage(base64)}
          title="تصویر محصول"
          defaultValue={item?.img}
          width={430}
          height={389}
        />

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