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,
  zValidateNumber,
  zValidateNumberOptional,
  zValidateString,
  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 { FormEnterLocations } from "../../components/FormItems/FormEnterLocation";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { getToastResponse } from "../../data/getToastResponse";
import { useUserProfileStore } from "../../context/zustand-store/userStore";
import { useState } from "react";
import Checkbox from "../../components/CheckBox/CheckBox";

const schema = z.object({
  name: zValidateString("نام سازمان"),
  national_unique_id: zValidateString("شناسه کشوری"),
  address: zValidateStringOptional("آدرس"),
  field_of_activity: zValidateAutoComplete("حوزه فعالیت"),
  province: zValidateNumber("استان"),
  city: zValidateNumber("شهر"),
  organization: zValidateNumberOptional("سازمان"),
  organizationType: zValidateNumber("سازمان"),
  is_repeatable: z.boolean(),
  free_visibility_by_scope: z.boolean(),
});

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

type FormValues = z.infer<typeof schema>;

export const AddOrganization = ({ getData, item }: AddPageProps) => {
  const { profile } = useUserProfileStore();

  const fieldOfActivityItems = [
    {
      key: "CO",
      value: "کشور",
      disabled:
        profile?.organization?.field_of_activity !== "CO" &&
        profile?.role?.type?.key !== "ADM",
    },
    {
      key: "PR",
      value: "استان",
      disabled: profile?.organization?.field_of_activity === "CI",
    },
    { key: "CI", value: "شهرستان", disabled: false },
  ];

  const showToast = useToast();
  const { closeModal } = useModalStore();

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    getValues,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: item?.name || "",
      address: item?.address || "",
      national_unique_id: item?.national_unique_id || "",
      free_visibility_by_scope: item?.free_visibility_by_scope || false,
      field_of_activity:
        item && item?.field_of_activity !== "EM"
          ? [item?.field_of_activity]
          : [profile?.organization?.field_of_activity || "CI"],
    },
  });

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

  const [LocationValues, setLocationValues] = useState<{
    province: string | any;
    city: string | any;
  }>({ province: "", city: "" });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        organization: {
          name: `${data?.name} ${
            data?.is_repeatable
              ? ""
              : data.field_of_activity[0] === "CI"
              ? LocationValues.city
              : LocationValues.province
          }`,

          ...(data.organizationType !== undefined && {
            type: data.organizationType,
          }),
          national_unique_id: data?.national_unique_id,
          province: data?.province,
          city: data?.city,
          ...(data.organization && {
            parent_organization: data.organization,
          }),
          field_of_activity: data.field_of_activity[0],
          free_visibility_by_scope: data.free_visibility_by_scope,
          address: data.address,
        },
      });
      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="organizationType"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.type?.id}
              title="نهاد"
              api={`auth/api/v1/organization-type`}
              keyField="id"
              secondaryKey="is_repeatable"
              tertiaryKey="org_type_field"
              valueField="name"
              error={!!errors.organizationType}
              errorMessage={errors.organizationType?.message}
              onChange={(r) => {
                setValue("organizationType", r.key1);
                setValue("is_repeatable", r.key2);
                setValue("field_of_activity", [r.key3 || "CI"]);
                trigger(["organizationType"]);
              }}
              onChangeValue={(r) => {
                if (!r.key2) {
                  setValue("name", r.value);
                } else {
                  setValue("name", item?.name || "");
                }
              }}
            />
          )}
        />

        <Controller
          name="field_of_activity"
          control={control}
          render={({ field }) => (
            <AutoComplete
              disabled={profile?.role?.type?.key !== "ADM"}
              data={fieldOfActivityItems}
              selectedKeys={field.value}
              onChange={(keys: (string | number)[]) => {
                setValue("field_of_activity", keys);
              }}
              error={!!errors.field_of_activity}
              helperText={errors.field_of_activity?.message}
              title="حوزه فعالیت"
            />
          )}
        />

        {getValues("is_repeatable") && (
          <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="national_unique_id"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شناسه کشوری"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.national_unique_id}
              helperText={errors.national_unique_id?.message}
            />
          )}
        />

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

        <Controller
          name="organization"
          control={control}
          render={() => (
            <>
              {getValues("province") && getValues("city") && (
                <FormApiBasedAutoComplete
                  defaultKey={item?.parent_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);
                  }}
                />
              )}
            </>
          )}
        />

        <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="free_visibility_by_scope"
          control={control}
          render={({ field }) => (
            <Checkbox
              checked={field.value}
              onChange={field.onChange}
              label="دسترسی به کل اطلاعات محدوده فعالیت سازمان"
            />
          )}
        />

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