import { Dispatch, FC, SetStateAction, useCallback, useMemo, useState } from "react";

import MultiSelect from "@/components/FormElements/MultiSelect";
import {
  ApiResponse,
  TAssignCustomerToCompanyCredentials,
  TCompaniesResponse,
} from "@/lib/api";
import { UseQueryResult } from "@tanstack/react-query";

interface IProps {
  companiesQuery: UseQueryResult<ApiResponse<TCompaniesResponse>, Error>;
  setCompanies: Dispatch<
    SetStateAction<TAssignCustomerToCompanyCredentials | undefined>
  >;
  defaultValues?: TAssignCustomerToCompanyCredentials;
}

const AssignToCompanyModalContent: FC<IProps> = ({
  companiesQuery,
  setCompanies,
  defaultValues,
}) => {
  const { data, isSuccess } = companiesQuery;
  const [selected, setSelected] = useState<string[]>(
    defaultValues?.companies ?? [],
  );

  const options = useMemo(() => {
    if (!isSuccess) return [];
    return (
      data?.data.companies?.map((item) => ({
        label: item.name,
        value: item.id,
      })) ?? []
    );
  }, [isSuccess, data?.data.companies]);

  const handleChange = useCallback(
    (event: { target: { value: string[] } }) => {
      const next = event.target.value;
      setSelected(next);
      setCompanies({ companies: next });
    },
    [setCompanies],
  );

  const noop = useCallback(() => {}, []);

  return (
    <div className="mt-5">
      <MultiSelect
        name="companies"
        label="Companies"
        items={options}
        value={selected}
        placeholder="Please select companies"
        required
        onChange={handleChange as any}
        onBlur={noop as any}
        ref={noop as any}
      />
    </div>
  );
};

export default AssignToCompanyModalContent;
