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 { 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";

const schema = z.object({
  unit: zValidateString("نام واحد فروش"),
});

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

type FormValues = z.infer<typeof schema>;

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

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      unit: item?.unit || "",
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        unit: data.unit,
      });

      showToast("عملیات با موفقیت انجام شد", "success");
      closeModal();
      getData();
    } catch (error: any) {
      if (error.status === 400) {
        showToast("این صفحه تکراری است!", "error");
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="unit"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام واحد فروش"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.unit}
              helperText={errors.unit?.message}
            />
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
