import { useState } from "react";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { useApiMutation, useApiRequest } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";

export const OtpAuthModal = ({ item, getData }: any) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const [selectedUser, setSelectedUser] = useState<(string | number)[]>([]);

  const { data: usersData } = useApiRequest({
    api: `/auth/api/v1/organization/${item?.assigned_org?.id}/org_users/`,
    method: "get",
    queryKey: ["orgUsers", item?.id],
  });

  const mutation = useApiMutation({
    api: `/tag/web/api/v1/tag_distribution_batch/${item?.id}/otp_auth/?otp_type=send`,
    method: "post",
  });

  const usersOptions =
    usersData?.map((user: any) => ({
      key: user?.user_receiver,
      value: `${user?.first_name} ${user?.last_name} - ${user?.mobile}`,
    })) ?? [];

  const onSubmit = async () => {
    if (selectedUser.length === 0) return;

    const selected = usersData?.find(
      (u: any) => u.user_receiver === selectedUser[0],
    );

    try {
      await mutation.mutateAsync(selected);
      showToast("ارسال با موفقیت انجام شد", "success");
      getData();
      closeModal();
    } catch (error: any) {
      showToast(error?.response?.data?.message || "خطا در ارسال!", "error");
    }
  };

  return (
    <Grid container column className="gap-3">
      <AutoComplete
        data={usersOptions}
        selectedKeys={selectedUser}
        onChange={(keys) => setSelectedUser(keys)}
        title="انتخاب کاربر"
      />

      <Button disabled={selectedUser.length === 0} onClick={onSubmit}>
        ارسال
      </Button>
    </Grid>
  );
};
