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,
} 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";
import {
  ArrowPathIcon,
  CheckBadgeIcon,
  PlusIcon,
  TrashIcon,
} from "@heroicons/react/24/outline";
import axios from "axios";

const schema = z.object({
  name: zValidateString("نام سازمان"),
  national_unique_id: zValidateString("شناسه کشوری"),
  field_of_activity: zValidateAutoComplete("حوزه فعالیت"),
  province: zValidateNumber("استان"),
  city: zValidateNumber("شهر"),
  organization: zValidateNumberOptional("سازمان"),
  organizationType: zValidateNumber("سازمان"),
  unique_unit_identity: zValidateNumberOptional("شناسه یکتا واحد"),
  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 || "",
      national_unique_id: item?.national_unique_id || "",
      unique_unit_identity: item?.unique_unit_identity || "",
      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 [addresses, setAddresses] = useState<
    { postal_code: string; address: string }[]
  >(
    item?.addresses?.length
      ? item.addresses.map((a: any) => ({
          postal_code: a.postal_code || "",
          address: a.address || "",
        }))
      : [{ postal_code: "", address: "" }],
  );

  const [isInquiryRequired, setIsInquiryRequired] = useState(false);
  const [inquiryPassed, setInquiryPassed] = useState(false);
  const [inquiryLoading, setInquiryLoading] = useState(false);

  const handleAddAddress = () => {
    setAddresses((prev) => [...prev, { postal_code: "", address: "" }]);
  };

  const handleRemoveAddress = (index: number) => {
    setAddresses((prev) => prev.filter((_, i) => i !== index));
  };

  const handleAddressChange = (
    index: number,
    field: "postal_code" | "address",
    value: string,
  ) => {
    setAddresses((prev) =>
      prev.map((item, i) => (i === index ? { ...item, [field]: value } : item)),
    );
  };

  const handleInquiry = async () => {
    const code = getValues("unique_unit_identity");
    if (!code) {
      showToast("لطفاً شناسه یکتا واحد را وارد کنید!", "error");
      return;
    }
    setInquiryLoading(true);
    try {
      await axios.get(
        `https://rsibackend.rasadyar.com/app/has_code_in_db/?code=${code}`,
      );
      setInquiryPassed(true);
      showToast("استعلام با موفقیت انجام شد!", "success");
    } catch (error: any) {
      if (error?.response?.status === 404) {
        setInquiryPassed(false);
        showToast("شناسه موجود نیست!", "error");
      } else {
        showToast("خطا در استعلام!", "error");
      }
    } finally {
      setInquiryLoading(false);
    }
  };

  const onSubmit = async (data: FormValues) => {
    if (isInquiryRequired && !data.unique_unit_identity) {
      showToast("شناسه یکتا واحد الزامی است!", "error");
      return;
    }
    if (isInquiryRequired && !inquiryPassed) {
      showToast("لطفاً ابتدا استعلام شناسه یکتا واحد را انجام دهید!", "error");
      return;
    }
    try {
      await mutation.mutateAsync({
        addresses: addresses.filter(
          (a) => a.postal_code.trim() || a.address.trim(),
        ),
        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,
          ...(data?.unique_unit_identity && {
            unique_unit_identity: data.unique_unit_identity,
          }),
          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,
        },
      });
      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"
              quaternaryKey="key"
              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.key4 === "U" || r.key4 === "CO") {
                  setIsInquiryRequired(true);
                } else {
                  setIsInquiryRequired(false);
                  setInquiryPassed(false);
                }
                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="unique_unit_identity"
          control={control}
          render={({ field }) => (
            <div className="flex items-start gap-2 w-full">
              <Textfield
                fullWidth
                placeholder={
                  isInquiryRequired
                    ? "شناسه یکتا واحد"
                    : "شناسه یکتا واحد (اختیاری)"
                }
                value={field.value}
                onChange={(e) => {
                  field.onChange(e);
                  setInquiryPassed(false);
                }}
                error={
                  !!errors.unique_unit_identity ||
                  (isInquiryRequired && !inquiryPassed && !!field.value)
                }
                helperText={
                  errors.unique_unit_identity?.message ||
                  (isInquiryRequired && inquiryPassed
                    ? "استعلام تایید شده"
                    : undefined)
                }
              />
              {isInquiryRequired && (
                <button
                  type="button"
                  onClick={handleInquiry}
                  disabled={inquiryLoading || !field.value}
                  className={`shrink-0 flex items-center gap-1 mt-[2px] px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                    inquiryPassed
                      ? "bg-green-500 text-white hover:bg-green-600"
                      : "bg-blue-500 text-white hover:bg-blue-600"
                  } disabled:opacity-50 disabled:cursor-not-allowed`}
                >
                  {inquiryLoading
                    ? "..."
                    : inquiryPassed
                      ? "تایید شده"
                      : "استعلام"}

                  {inquiryPassed && !inquiryLoading ? (
                    <CheckBadgeIcon className="w-4 h-4 text-white" />
                  ) : (
                    <ArrowPathIcon className="w-4 h-4 text-white" />
                  )}
                </button>
              )}
            </div>
          )}
        />

        <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);
                  }}
                />
              )}
            </>
          )}
        />

        <div className="flex flex-col gap-2 w-full">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-gray-700">آدرس‌ها</span>
            <button
              type="button"
              onClick={handleAddAddress}
              className="flex items-center gap-1 text-sm text-blue-500 dark:text-blue-300 hover:text-blue-800 transition-colors"
            >
              <PlusIcon className="w-4 h-4" />
              افزودن آدرس
            </button>
          </div>
          {addresses.map((addr, index) => (
            <div
              key={index}
              className="flex items-start gap-2 p-3 border border-gray-200 rounded-lg"
            >
              <div className="flex flex-col gap-2 flex-1">
                <Textfield
                  fullWidth
                  placeholder="کد پستی"
                  value={addr.postal_code}
                  onChange={(e) =>
                    handleAddressChange(index, "postal_code", e.target.value)
                  }
                />
                <Textfield
                  fullWidth
                  placeholder="آدرس"
                  value={addr.address}
                  onChange={(e) =>
                    handleAddressChange(index, "address", e.target.value)
                  }
                />
              </div>
              {addresses.length > 1 && (
                <button
                  type="button"
                  onClick={() => handleRemoveAddress(index)}
                  className="mt-2 text-red-500 hover:text-red-700 transition-colors shrink-0"
                >
                  <TrashIcon className="w-5 h-5" />
                </button>
              )}
            </div>
          ))}
        </div>

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

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