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 "@/shared/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 FormSelectShippingTimesProps extends SelectProps {
  name: string;
  label?: string;
  placeholder?: string;
  showRequired?: boolean;
  disabled?: boolean;
  isMulti?: boolean;
}

const Comp: React.FC<FormSelectShippingTimesProps> = ({
  name,
  label,
  showRequired = true,
  disabled,
  placeholder,
  isMulti = false,
  ...props
}) => {
  const { data, isLoading } = UseFetch<any>({
    endpoint: "guest/shipping-times?paginate=0",
  });
  const options: OptionsType[] =
    data?.data?.map((item: any) => ({
      label: `${item?.delivery_start_time} ${item?.delivery_start_period} - ${item?.delivery_end_time} ${item?.delivery_end_period}`,
      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" : "#F3F6FC",
      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 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 FormSelectShippingTimes = dynamic(() => Promise.resolve(Comp), {
  ssr: false,
});

export default FormSelectShippingTimes;
