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 AutoComplete from "../../components/AutoComplete/AutoComplete";
import { getToastResponse } from "../../data/getToastResponse";
import { useState, useEffect } from "react";

type SettingsType = "purchase_policy" | "service_area";

type AddActivityTypeSettingsProps = {
  item: any;
  settingsType: SettingsType;
  onUpdate: () => void;
};

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

export const AddActivityTypeSettings = ({
  item,
  settingsType,
  onUpdate,
}: AddActivityTypeSettingsProps) => {
  const showToast = useToast();
  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, item?.id],
    enabled: !!provinceId && settingsType === "service_area",
  });

  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 mutation = useApiMutation({
    api: `/auth/api/v1/organization/${item?.id}/`,
    method: "put",
  });

  if (settingsType === "purchase_policy") {
    const schema = z.object({
      purchase_policy: zValidateString("محدودیت دریافت نهاده"),
    });

    type FormValues = z.infer<typeof schema>;

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

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

    return (
      <form onSubmit={handleSubmit(onSubmit)} className="min-w-[200px]">
        <Grid container column className="gap-1">
          <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=""
                size="small"
              />
            )}
          />
          <Button type="submit" size="small" className="w-full">
            ثبت
          </Button>
        </Grid>
      </form>
    );
  }

  // service_area form
  const schema = z.object({
    service_area: zValidateAutoComplete("محدوده فعالیت"),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      service_area: defaultCityIds as (string | number)[],
    },
  });

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

  if (!provinceId) {
    return <span className="text-xs text-gray-500">-</span>;
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="min-w-[200px]">
      <Grid container column className="gap-1">
        <Controller
          name="service_area"
          control={control}
          render={() => (
            <AutoComplete
              data={citiesData}
              selectedKeys={selectedCities}
              onChange={(keys: (string | number)[]) => {
                setSelectedCities(keys);
                setValue("service_area", keys as any);
                trigger("service_area");
              }}
              error={!!errors.service_area}
              helperText={errors.service_area?.message}
              title=""
              multiselect={true}
              size="small"
            />
          )}
        />
        <Button type="submit" size="small" className="w-full">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
