import { zodResolver } from "@hookform/resolvers/zod";
import Button from "../../components/Button/Button";
import { Grid } from "../../components/Grid/Grid";
import { useForm, Controller } from "react-hook-form";
import {
  zValidateAutoComplete,
  zValidateString,
} from "../../data/getFormTypeErrors";
import { z } from "zod";
import { useApiMutation, useApiRequest } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { getToastResponse } from "../../data/getToastResponse";
import { useState, useEffect } from "react";

const schema = z.object({
  service_area: zValidateAutoComplete("محدوده فعالیت"),
  purchase_policy: zValidateString("محدودیت دریافت نهاده برای دامدار"),
});

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

type FormValues = z.infer<typeof schema>;

const purchasePolicyItems = [
  {
    key: "INTERNAL_ONLY",
    value: "بر اساس تعاونی",
  },
  {
    key: "CROSS_COOP",
    value: "برای کل استان",
  },
];

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

  const defaultCityIds = item?.org_service_area
    ? item.org_service_area.map((city: any) => city.id)
    : [];

  const [selectedCities, setSelectedCities] =
    useState<(string | number)[]>(defaultCityIds);
  const [citiesData, setCitiesData] = useState<
    { key: number; value: string }[]
  >([]);

  const provinceId = item?.province_id;

  const { data: citiesApiData } = useApiRequest({
    api: `/auth/api/v1/city/`,
    method: "get",
    params: { province: provinceId },
    queryKey: ["cities", provinceId],
    enabled: !!provinceId,
  });

  useEffect(() => {
    if (citiesApiData) {
      const cities = Array.isArray(citiesApiData)
        ? citiesApiData
        : citiesApiData?.results || [];
      const formattedCities = cities.map((city: any) => ({
        key: city.id,
        value: city.name,
      }));
      setCitiesData(formattedCities);
    }
  }, [citiesApiData]);

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      purchase_policy: item?.org_purchase_policy || "",
      service_area: defaultCityIds,
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        organization: {
          service_area: selectedCities,
          purchase_policy: data.purchase_policy,
        },
      });
      showToast(getToastResponse(item, "نوع فعالیت"), "success");
      getData();
      closeModal();
    } catch (error: any) {
      showToast(
        error?.response?.data?.message || "خطا در ثبت اطلاعات!",
        "error"
      );
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="purchase_policy"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={purchasePolicyItems}
              selectedKeys={field.value ? [field.value] : []}
              onChange={(keys: (string | number)[]) => {
                setValue("purchase_policy", keys[0] as string);
                trigger("purchase_policy");
              }}
              error={!!errors.purchase_policy}
              helperText={errors.purchase_policy?.message}
              title="محدودیت دریافت نهاده برای دامدار"
            />
          )}
        />

        {provinceId && (
          <Controller
            name="service_area"
            control={control}
            render={() => (
              <AutoComplete
                data={citiesData}
                selectedKeys={selectedCities}
                onChange={(keys: (string | number)[]) => {
                  setSelectedCities(keys);
                  setValue("service_area", keys);
                  trigger("service_area");
                }}
                error={!!errors.service_area}
                helperText={errors.service_area?.message}
                title="محدوده فعالیت"
                multiselect={true}
              />
            )}
          />
        )}

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