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

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

export const AddPos = ({ getData, item }: AddPosProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const { profile } = useUserProfileStore();

  const schema = z.object({
    acceptor: zValidateString("پذیرنده"),
    terminal: zValidateString("ترمینال"),
    serial: zValidateEnglishString("سریال"),
    password: zValidateEnglishString("کلمه عبور"),
    organization:
      profile?.role?.type?.key === "ADM"
        ? zValidateAutoComplete("سازمان")
        : zValidateAutoCompleteOptional(),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      acceptor: item?.acceptor || "",
      terminal: item?.terminal || "",
      serial: item?.serial || "",
      password: item?.password || "",
      organization: item?.organization?.id ? [item?.organization?.id] : [],
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        acceptor: data.acceptor,
        terminal: data.terminal,
        serial: data.serial,
        password: data.password,
        ...(profile?.role?.type?.key === "ADM" && data.organization?.length
          ? { organization: data.organization[0] }
          : {}),
      });

      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">
        {profile?.role?.type?.key === "ADM" && (
          <Controller
            name="organization"
            control={control}
            render={() => (
              <>
                <FormApiBasedAutoComplete
                  defaultKey={item?.organization?.id}
                  title="انتخاب شرکت پرداختی"
                  api={`pos_device/web/v1/pos/device/psp_organizations`}
                  keyField="id"
                  valueField="name"
                  error={!!errors.organization}
                  errorMessage={errors.organization?.message}
                  onChange={(r) => {
                    setValue("organization", [r]);
                  }}
                />
              </>
            )}
          />
        )}

        <Controller
          name="acceptor"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شماره پذیرنده"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.acceptor}
              helperText={errors.acceptor?.message}
            />
          )}
        />
        <Controller
          name="terminal"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شماره ترمینال"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.terminal}
              helperText={errors.terminal?.message}
            />
          )}
        />
        <Controller
          name="serial"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="سریال"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.serial}
              helperText={errors.serial?.message}
            />
          )}
        />
        <Controller
          name="password"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کلمه عبور"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.password}
              helperText={errors.password?.message}
            />
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
