import {
  Dispatch,
  FC,
  RefObject,
  SetStateAction,
  useEffect,
  useState,
} from "react";

import { useForm } from "react-hook-form";
import { TAssignCustomerToCompanyCredentials } from "@/lib/api";
import { useCompanyFullList } from "@/hooks/queries";
import { ILabelValue } from "@/types/shared";
import { Select } from "@/components/FormElements/select";
import { Building } from "@/components/Layouts/sidebar/icons";
import { FormErrorMessages } from "@/constants/Texts";

interface IProps {
  setCompanies: Dispatch<
    SetStateAction<TAssignCustomerToCompanyCredentials | null>
  >;
}
const AssignToCompanyModalContent: FC<IProps> = ({ setCompanies }) => {
  const [options, setOptions] = useState<ILabelValue[]>([]);

  const { data, status, isSuccess } = useCompanyFullList();
  const { handleSubmit, register } =
    useForm<TAssignCustomerToCompanyCredentials>();

  useEffect(() => {
    if (isSuccess) {
      setOptions(
        data.data.companies
          ? data.data.companies?.map((item) => ({
              label: item.name,
              value: item.id,
            }))
          : [],
      );
    }
  }, [status]);

  const assignCompany = (data: TAssignCustomerToCompanyCredentials) => {
    setCompanies(data);
  };
  return (
    <form className="mt-5" onSubmit={handleSubmit(assignCompany)}>
      <Select
        {...register("company_ids", {
          required: { message: FormErrorMessages.required, value: true },
          onChange: (e) => {
            setCompanies({
              company_ids: [e.target.value],
            });
          },
        })}
        name="company_ids"
        label="Companies"
        items={options}
        prefixIcon={<Building />}
        placeholder="Please Select company"
      />
    </form>
  );
};

export default AssignToCompanyModalContent;
