import {
  zValidateAutoComplete,
  zValidateEnglishString,
  zValidateMobile,
  zValidateNationalCodeOptional,
  zValidateNumber,
  zValidateString,
  zValidateStringOptional,
} from "../../data/getFormTypeErrors";
import { z } from "zod";
import { Grid } from "../../components/Grid/Grid";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Textfield from "../../components/Textfeild/Textfeild";
import Button from "../../components/Button/Button";
import DatePicker from "../../components/date-picker/DatePicker";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { FormEnterLocations } from "../../components/FormItems/FormEnterLocation";
import { useApiMutation } from "../../utils/useApiRequest";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import { useToast } from "../../hooks/useToast";
import { useDrawerStore } from "../../context/zustand-store/appStore";
import Typography from "../../components/Typography/Typography";
import { useFetchProfile } from "../../hooks/useFetchProfile";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

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

const owenerships = [
  { key: "N", value: "حقیقی", disabled: false },
  { key: "L", value: "حقوقی", disabled: false },
];

export const AddUser = ({ getData, item }: AddAccessProps) => {
  const { getProfile } = useFetchProfile();

  const { profile } = useUserProfileStore();
  const isAdmin = profile?.role?.type?.key === "ADM";

  const schema = z
    .object({
      username: zValidateEnglishString("نام کاربری"),
      password: item
        ? zValidateStringOptional("گلمه عبور")
        : zValidateString("کلمه عبور"),
      first_name: zValidateString("نام"),
      last_name: zValidateString("نام خانوادگی"),
      role: zValidateNumber("نقش"),
      organization: zValidateNumber("سازمان"),
      phone: zValidateNumber("تلفن"),
      mobile: zValidateMobile("موبایل"),
      national_code: zValidateNationalCodeOptional("کد ملی"),
      birthdate: zValidateString("تاریخ تولد"),
      ownership: zValidateAutoComplete("مالکیت"),
      address: zValidateString("آدرس"),
      province: zValidateNumber("استان"),
      city: zValidateNumber("شهر"),
      unit_name: zValidateStringOptional("نام واحد حقوقی"),
      unit_national_id: zValidateStringOptional("شناسه ملی واحد حقوقی"),
    })
    .refine(
      (data) => {
        if (data.ownership?.[0] === "L") {
          return !!data.unit_name;
        }
        return true;
      },
      {
        message: "نام واحد حقوقی نمیتواند خالی باشد",
        path: ["unit_name"],
      }
    )
    .refine(
      (data) => {
        if (data.ownership?.[0] === "L") {
          return !!data.unit_national_id;
        }
        return true;
      },
      {
        message: "شناسه ملی واحد حقوقی نمیتواند خالی باشد",
        path: ["unit_national_id"],
      }
    );

  type FormValues = z.infer<typeof schema>;

  const showToast = useToast();
  const { closeDrawer } = useDrawerStore();
  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    getValues,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      username: item?.user?.username || "",
      password: "",
      first_name: item?.user?.first_name || "",
      last_name: item?.user?.last_name || "",
      phone: item?.user?.phone || "",
      mobile: item?.user?.mobile || "",
      national_code: item?.user?.national_code || "",
      birthdate: item?.birthdate || "",
      ownership: item ? [item?.user?.ownership] : [],
      address: item?.user?.address || "",
      province: item?.user?.province || "",
      city: item?.user?.city || "",
      role: item?.role?.id || "",
      unit_name: item?.user?.unit_name || "",
      unit_national_id: item?.user?.unit_national_id || "",
      // is_herd_owner: item ? [`${item?.user?.is_herd_owner}`] : ["false"],
      // selectedAccessId: [],
    },
  });

  const mutationAddUser = useApiMutation({
    api: `/auth/api/v1/user/${item ? item.user?.id + "/" : ""}`,
    method: item ? "put" : "post",
    disableBackdrop: false,
  });

  const onSubmit = async (data: FormValues) => {
    let d = {
      ...(data.username !== item?.user?.username && {
        username: data.username.toLowerCase(),
      }),
      ...(data.password && { password: data.password }),
      first_name: data.first_name,
      last_name: data.last_name,
      is_active: true,
      mobile: data.mobile,
      phone: data.phone,
      national_code: data.national_code,
      birthdate: data.birthdate + " 10:00:00.520088 +00:00",
      nationality: "ایرانی",
      ownership: data.ownership[0],
      address: data.address,
      photo: null,
      province: data.province,
      city: data.city,
      otp_status: false,
      ...(data.unit_name && { unit_name: data.unit_name }),
      ...(data.unit_national_id && { unit_national_id: data.unit_national_id }),
      // is_herd_owner: data.is_herd_owner[0] === "false" ? false : true,
      user_relations: {
        ...(data.organization !== undefined && {
          organization: data.organization,
        }),
        ...(item && {
          id: item?.id,
        }),
        role: data.role,
        // permissions: data.selectedAccessId,
      },
    };

    try {
      await mutationAddUser.mutateAsync(d);
      showToast(`کاربر با موفقیت ${item ? "ویرایش" : "ایجاد"} شد`, "success");
      getData();
      getProfile();
      closeDrawer();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast("کاربر با این مشخصات از قبل وجود دارد!", "error");
      } else {
        showToast(`خطا در ${item ? "ویرایش" : "ایجاد"} کاربر!`, "error");
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        {item && (
          <Typography
            sign="info"
            color="text-red-600 dark:text-red-300"
            className=""
            variant="caption"
          >
            فیلدهایی که نیاز به تغییر ندارند را ویرایش نکنید!
          </Typography>
        )}

        <Controller
          name="ownership"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={owenerships}
              selectedKeys={field.value}
              onChange={(keys: (string | number)[]) => {
                setValue("ownership", keys);
                trigger(["ownership", "unit_name", "unit_national_id"]);
              }}
              error={!!errors.ownership}
              helperText={errors.ownership?.message}
              title="مالکیت"
            />
          )}
        />

        {!!getValues("ownership").length && (
          <Grid container column className="gap-2">
            <Controller
              name="first_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.first_name}
                  helperText={errors.first_name?.message}
                />
              )}
            />

            <Controller
              name="last_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام خانوادگی"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.last_name}
                  helperText={errors.last_name?.message}
                />
              )}
            />

            <Controller
              name="phone"
              control={control}
              render={({ field }) => (
                <Textfield
                  isNumber
                  fullWidth
                  placeholder="تلفن"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.phone}
                  helperText={errors.phone?.message}
                />
              )}
            />

            <Controller
              name="mobile"
              control={control}
              render={({ field }) => (
                <Textfield
                  isNumber
                  fullWidth
                  placeholder="موبایل"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.mobile}
                  helperText={errors.mobile?.message}
                />
              )}
            />

            <Controller
              name="national_code"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="کد ملی"
                  isNumber
                  value={field.value || ""}
                  onChange={field.onChange}
                  error={!!errors.national_code}
                  helperText={errors.national_code?.message}
                />
              )}
            />

            <DatePicker
              value={item?.user?.birthdate || ""}
              minYear={1300}
              label="تاریخ تولد"
              size="medium"
              onChange={(r) => {
                setValue("birthdate", r);
              }}
            />

            <Controller
              name="username"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام کاربری"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.username}
                  helperText={errors.username?.message}
                />
              )}
            />

            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="کلمه عبور"
                  password
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.password}
                  helperText={errors.password?.message}
                />
              )}
            />

            <Controller
              name="role"
              control={control}
              render={() => (
                <FormApiBasedAutoComplete
                  defaultKey={item?.role?.id}
                  title="نقش"
                  api={"auth/api/v1/role/"}
                  keyField="id"
                  valueField="role_name"
                  filterAddress={["type", "key"]}
                  filterValue={isAdmin ? [] : ["ADM"]}
                  onChange={(r) => {
                    setValue("role", r);
                    trigger(["role"]);
                  }}
                  error={!!errors.role}
                  errorMessage={errors.role?.message}
                />
              )}
            />

            <Controller
              name="province"
              control={control}
              render={() => (
                <FormEnterLocations
                  cityValue={item?.user?.city}
                  provinceValue={item?.user?.province}
                  cityError={!!errors.city}
                  provincError={!!errors.province}
                  cityErrorMessage={errors.city?.message}
                  provinceErrMessage={errors.province?.message}
                  roleControlled
                  onChange={async (locations) => {
                    setValue("province", locations.province);
                    setValue("city", locations.city);
                    if (locations.province || locations.city)
                      await trigger(["province", "city"]);
                  }}
                />
              )}
            />

            <Controller
              name="address"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="آدرس"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.address}
                  helperText={errors.address?.message}
                />
              )}
            />

            <Controller
              name="organization"
              control={control}
              render={() => (
                <>
                  {getValues("province") && getValues("city") && (
                    <FormApiBasedAutoComplete
                      defaultKey={item?.organization?.id}
                      title="سازمان"
                      api={`auth/api/v1/organization/organizations_by_province?province=${getValues(
                        "province"
                      )}`}
                      keyField="id"
                      valueField="name"
                      error={!!errors.organization}
                      errorMessage={errors.organization?.message}
                      onChange={(r) => {
                        setValue("organization", r);
                      }}
                    />
                  )}
                </>
              )}
            />

            {getValues("ownership")?.[0] === "L" && (
              <>
                <Controller
                  name="unit_name"
                  control={control}
                  render={({ field }) => (
                    <Textfield
                      fullWidth
                      placeholder="نام واحد حقوقی"
                      value={field.value}
                      onChange={field.onChange}
                      error={!!errors.unit_name}
                      helperText={errors.unit_name?.message}
                    />
                  )}
                />

                <Controller
                  name="unit_national_id"
                  control={control}
                  render={({ field }) => (
                    <Textfield
                      fullWidth
                      placeholder="شناسه ملی واحد حقوقی"
                      isNumber
                      value={field.value}
                      onChange={field.onChange}
                      error={!!errors.unit_national_id}
                      helperText={errors.unit_national_id?.message}
                    />
                  )}
                />
              </>
            )}

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