import { useState } from "react";
import { Grid } from "../../../components/Grid/Grid";
import Button from "../../../components/Button/Button";
import AutoComplete from "../../../components/AutoComplete/AutoComplete";
import Textfield from "../../../components/Textfeild/Textfeild";
import Checkbox from "../../../components/CheckBox/CheckBox";
import { useApiMutation, useApiRequest } from "../../../utils/useApiRequest";
import { useToast } from "../../../hooks/useToast";
import { useModalStore } from "../../../context/zustand-store/appStore";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  zValidateString,
  zValidateMobile,
  zValidateNationalCode,
} from "../../../data/getFormTypeErrors";

const schema = z.object({
  first_name: zValidateString("نام"),
  last_name: zValidateString("نام خانوادگی"),
  mobile: zValidateMobile("موبایل"),
  national_code: zValidateNationalCode("کد ملی"),
});

type FormValues = z.infer<typeof schema>;

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

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      first_name: "",
      last_name: "",
      mobile: "",
      national_code: "",
    },
  });

  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 submitPayload = async (payload: any) => {
    try {
      await mutation.mutateAsync(payload);
      showToast("ارسال با موفقیت انجام شد", "success");
      getData();
      closeModal();
    } catch (error: any) {
      showToast(error?.response?.data?.message || "خطا در ارسال!", "error");
    }
  };

  const onManualSubmit = async (data: FormValues) => {
    await submitPayload(data);
  };

  const onAutoCompleteSubmit = async () => {
    if (selectedUser.length === 0) return;
    const selected = usersData?.find(
      (u: any) => u.user_receiver === selectedUser[0],
    );
    await submitPayload(selected);
  };

  return (
    <Grid container column className="gap-3">
      <Checkbox
        label="ورود دستی اطلاعات کاربر"
        checked={isManual}
        onChange={(e) => {
          setIsManual(e.target.checked);
          setSelectedUser([]);
          reset();
        }}
      />

      {isManual ? (
        <form onSubmit={handleSubmit(onManualSubmit)}>
          <Grid container column className="gap-3">
            <Controller
              name="first_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.first_name}
                  helperText={errors.first_name?.message}
                />
              )}
            />

            <Controller
              name="last_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام خانوادگی"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.last_name}
                  helperText={errors.last_name?.message}
                />
              )}
            />

            <Controller
              name="mobile"
              control={control}
              render={({ field }) => (
                <Textfield
                  isNumber
                  fullWidth
                  placeholder="شماره موبایل"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.mobile}
                  helperText={errors.mobile?.message}
                />
              )}
            />

            <Controller
              name="national_code"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  isNumber
                  placeholder="کد ملی"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.national_code}
                  helperText={errors.national_code?.message}
                />
              )}
            />

            <Button type="submit">ارسال</Button>
          </Grid>
        </form>
      ) : (
        <>
          <AutoComplete
            data={usersOptions}
            selectedKeys={selectedUser}
            onChange={(keys) => setSelectedUser(keys)}
            title="انتخاب کاربر"
          />

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