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,
  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 AutoComplete from "../../components/AutoComplete/AutoComplete";
import Checkbox from "../../components/CheckBox/CheckBox";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";

const schema = z.object({
  name: zValidateString("نام نهاد "),
  org_type_field: zValidateAutoComplete("حوزه فعالیت"),
  is_repeatable: z.boolean(),
  parent: zValidateNumberOptional("نهاد والد"),
});

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

type FormValues = z.infer<typeof schema>;

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

  const fieldOfActivityItems = [
    {
      key: "CO",
      value: "کشور",
    },
    {
      key: "PR",
      value: "استان",
    },
    { key: "CI", value: "شهرستان" },
  ];

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: item?.name || "",
      org_type_field: item?.org_type_field ? [item?.org_type_field] : ["CO"],
      is_repeatable: item?.is_repeatable || false,
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data?.name,
        org_type_field: data?.org_type_field[0],
        is_repeatable: data?.is_repeatable || false,
        ...(data?.parent ? { parent: data?.parent } : {}),
      });
      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="parent"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.parent?.id}
              title="نهاد والد (اختیاری)"
              api={`auth/api/v1/organization-type`}
              keyField="id"
              valueField="name"
              error={!!errors.parent}
              errorMessage={errors.parent?.message}
              onChange={(r) => {
                setValue("parent", r);
              }}
            />
          )}
        />

        <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="org_type_field"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={fieldOfActivityItems}
              selectedKeys={field.value}
              onChange={(keys: (string | number)[]) => {
                setValue("org_type_field", keys);
              }}
              error={!!errors.org_type_field}
              helperText={errors.org_type_field?.message}
              title="حوزه فعالیت نهاد"
            />
          )}
        />

        <Controller
          name="is_repeatable"
          control={control}
          render={({ field }) => (
            <Checkbox
              checked={field.value}
              onChange={field.onChange}
              label="قابلیت تکرار نام"
            />
          )}
        />

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