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 {
  zValidateBase64Optional,
  zValidateNumber,
  zValidateStringOptional,
} 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 FileUploader from "../../components/FIleUploader/FileUploader";
import Typography from "../../components/Typography/Typography";

type Props = {
  getData: () => void;
  item?: any;
  code?: string;
  remainWeight?: number;
};

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

  const schema = z.object({
    weight: zValidateNumber("وزن"),
    lading_number: zValidateNumber("شماره بارنامه"),
    delivery_address: zValidateStringOptional("بارنامه"),
    notes: zValidateStringOptional("بارنامه"),
    document: zValidateBase64Optional("سند بارنامه"),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      weight: item?.weight || "",
      lading_number: item?.lading_number || "",
      notes: item?.notes || "",
      delivery_address: item?.delivery_address || "",
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        quota: Number(code),
        weight: data?.weight,
        lading_number: data?.lading_number,
        delivery_address: data?.delivery_address,
        notes: data?.notes,
        document: data?.document,
        ...(item ? { organization: item?.organization } : {}),
      });
      showToast(getToastResponse(item, ""), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 400) {
        showToast(
          error?.response?.data?.detail || error?.response?.data?.message,
          "error"
        );
        closeModal();
      } else 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">
        <Grid container className="justify-center w-full">
          <Typography variant="body2" className="items-center" sign="info">
            {" "}
            مانده قابل ورود به انبار:
            <span className="font-bold text-red-500">
              {remainWeight?.toLocaleString()}{" "}
            </span>
          </Typography>
        </Grid>

        <Controller
          name="weight"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="وزن"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.weight}
              helperText={errors.weight?.message}
            />
          )}
        />
        <Controller
          name="lading_number"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شماره بارنامه"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.lading_number}
              helperText={errors.lading_number?.message}
            />
          )}
        />

        <Controller
          name="delivery_address"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="محل دریافت"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.delivery_address}
              helperText={errors.delivery_address?.message}
            />
          )}
        />
        <Controller
          name="document"
          control={control}
          render={() => (
            <FileUploader
              defaultValue={item?.document}
              onFileSelected={(base64) => {
                setValue("document", base64);
                trigger("document");
              }}
              error={errors.document?.message}
            />
          )}
        />
        <Controller
          name="notes"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="توضیحات"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.notes}
              helperText={errors.notes?.message}
            />
          )}
        />

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