import React from "react";
import { useFormContext } from "react-hook-form";
import Select, { Props as SelectProps } from "react-select";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "../ui/form";
import { useTranslations } from "next-intl";
import UseFetch from "@/hooks/UseFetch";
import dynamic from "next/dynamic";
export interface OptionsType {
  value: string;
  label: string;
}
interface FormGenralSelectProps extends SelectProps {
  endpoint: string;
  general?: boolean;
  enabled?: boolean;
  name: string;
  label?: string;
  placeholder?: string;
  showRequired?: boolean;
  disabled?: boolean;
  isMulti?: boolean;
}

const Comp: React.FC<FormGenralSelectProps> = ({
  endpoint,
  general = false,
  enabled = true,
  name,
  label,
  showRequired = true,
  disabled,
  placeholder,
  isMulti = false,
  ...props
}) => {
  const { data, isLoading } = UseFetch<any>({
    endpoint: endpoint,
    general: general,
    enabled: enabled,
  });
  const options: OptionsType[] =
    data?.data?.map((item: any) => ({
      label:
        item?.name ||
        item?.title ||
        item?.value ||
        item?.full_name ||
        `${item?.location?.country?.name} - ${item?.location?.city?.name} - ${item?.location?.district?.name}` ||
        "",
      value: item.id,
    })) || [];
  const form = useFormContext();
  const t = useTranslations("LABELS");
  const {
    setValue,
    getValues,
    formState: { errors },
    trigger,
  } = form;

  const styles = {
    control: (provided: any, state: any) => ({
      ...provided,
      width: "100%",
      minHeight: "48px",
      backgroundColor: state.isDisabled ? "#f3f4f6" : "#ffffff",
      borderColor:
        errors[name] && errors[name]?.message
          ? "#ef233c"
          : getComputedStyle(document.documentElement)
              .getPropertyValue("--color-border")
              .trim() || "#cacaca",
      borderRadius: "12px",
      padding: "0 8px",
      fontSize: "14px",
      zIndex: 0,
      opacity: state.isDisabled ? 0.7 : 1,
      cursor: state.isDisabled ? "not-allowed" : "default",
    }),
    indicatorSeparator: () => ({
      display: "none",
    }),
    placeholder: (provided: any, state: any) => ({
      ...provided,
      fontSize: "14px",
      color: state.isDisabled ? "#9ca3af" : "#2d2d2db2",
    }),
    option: (provided: any, state: any) => ({
      ...provided,
      fontSize: "14px",
      color: state.isDisabled ? "#9ca3af" : "#1a1919b2",
    }),
    menu: (provided: any) => ({
      ...provided,
      zIndex: 9999,
    }),
    menuPortal: (provided: any) => ({
      ...provided,
      zIndex: 9999,
    }),
  };
  const fieldValue = getValues(name) || "";
  const selectedOptions = isMulti
    ? options.filter((option) => {
        return (
          Array.isArray(fieldValue) &&
          fieldValue?.find(
            (ele: any) =>
              (typeof ele === "object" ? ele.id : ele) == option.value,
          )
        );
      })
    : options.find((option) => option.value == fieldValue);
  return (
    <FormField
      control={form.control}
      name={name}
      render={({ field }) => (
        <FormItem>
          <div className="flex items-center gap-2">
            {label && (
              <FormLabel className=" text-text-primary font-medium text-sm leading-6 px-4 ">
                {t(label)}
                {showRequired && (
                  <span className="text-error mx-1 text-lg translate-y-1 inline-block">
                    *
                  </span>
                )}
              </FormLabel>
            )}
          </div>
          <FormControl>
            <Select
              {...field}
              isMulti={isMulti}
              isLoading={isLoading}
              isDisabled={disabled}
              options={options}
              onChange={(option) => {
                if (isMulti) {
                  setValue(
                    name,
                    (option as OptionsType[]).map((o) => o.value) ?? [],
                  );
                } else {
                  setValue(name, option ? (option as OptionsType).value : "");
                }
                trigger(name);
              }}
              styles={styles}
              defaultValue={options.find(
                (option) => option.value == field.value,
              )}
              // value={options.find((option) => option.value == field.value)}
              value={getValues(name) && selectedOptions}
              placeholder={t("select", {
                name: placeholder ? t(placeholder || "") : "",
              })}
              {...props}
            />
          </FormControl>
          <FormMessage />
        </FormItem>
      )}
    />
  );
};
const FormGenralSelect = dynamic(() => Promise.resolve(Comp), { ssr: false });

export default FormGenralSelect;
