import React, { useEffect, useState } from "react";
import Modal from "react-bootstrap/Modal";
import { useForm, Controller } from "react-hook-form";
import { FormControl, Tooltip, OverlayTrigger, Button } from "react-bootstrap";


import {
  CustomerChildUpdate,
  AssociateChildUpdate,
  GetAccociateDetails,
} from "@/services/profile";
import { yupResolver } from "@hookform/resolvers/yup";
import { getStates, adminUser } from "@/services/public";
import * as Yup from "yup";
import "react-toastify/dist/ReactToastify.css";
import { ToastContainer, toast } from "react-toastify";
import { useSession } from "next-auth/react";
const schema = Yup.object().shape({
  name: Yup.string()
    .required("Name is required")
    .max(50, "Maximum 50 characters allowed"),
  username: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
  city: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
  state: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
  phone: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),

  // email: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
  email: Yup.string()
    .max(50, "Maximum 50 characters allowed")
    .email("billing email address is not valid")
    .required("billing email is required"),

  role_label: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
});

function MyVerticallyCenteredModals(props: any) {  
  const val = Yup.object().shape({
    customer: Yup.string()
      .required("Name is required")
      .max(50, "Maximum 50 characters allowed"),
    contact: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    city: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    state: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    phone: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    email: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    sales_rep: Yup.string().max(50, "Maximum 50 characters allowed").nullable(),
    is_sent_rate: Yup.string().default("0").nullable(),
  });
  const [formattedPhone, setFormattedPhone] = useState(null);
  const [draydexemail, setDraydexEmail] = useState(false);
  const [phoneErrorVisible, setPhoneErrorVisible] = useState(false);
  const info = props?.child?.rowData;
  const infoChild = props?.child?.setListingRef;
  const isSent = info?.is_sent_rate == "YES" ? "1" : "0";
  const {
    handleSubmit,
    control,
    reset,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(val),
  });
  useEffect(() => {
    setValue("customer", info?.customer);
    setValue("contact", info?.contact);
    setValue("city", info?.city);
    setValue("state", info?.state);
    setValue("email", info?.email);
    setValue("sales_rep", info?.sales_rep);
    setValue("is_sent_rate", isSent);
    setFormattedPhone(info?.phone);
    setValue("phone", info?.phone);
  }, [info, isSent]);
  const [states, setStates] = useState([]);
  const { data } = useSession();
  const token = data?.user?.image;
  useEffect(() => {
    getStates()
      .then((response) => {
        setStates(response?.data);
      })
      .catch((error) => {
        console.error("Error fetching states:", error);
      });
  }, []);
  const filteredStates = states?.filter(
    (state) => state?.country_code === "US"
  );
  const onSubmit = async (data1) => {
    toast.dismiss();
    if (
      data1?.is_sent_rate === "1" &&
      (!data1?.email || data1?.email.length === 0)
    ) {
      setDraydexEmail(true);
    } else {
      setDraydexEmail(false);
      if (!phoneErrorVisible) {
        const response = await CustomerChildUpdate(token, data1, info?.id);
        if (response.status === "success") {
          infoChild(true);

          reset();
          toast.success(response.message, {
            position: toast.POSITION.TOP_CENTER,
          });
          props.onHide();
        } else {
          toast.error(response.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      }
    }
  };
  const handleCancel = () => {
    setDraydexEmail(false);
    setPhoneErrorVisible(false);
    props.onHide();
    reset();
  };

  const handlePhoneChange = (event: { target: { value: any } }) => {
    let inputValue = event.target.value;
    const cleanedInput = inputValue.replace(/\D/g, "");
    const formattedNumber = cleanedInput.slice(0, 10);
    if (formattedNumber.length >= 1 && formattedNumber.length <= 9) {
      setPhoneErrorVisible(true);
    } else {
      setPhoneErrorVisible(false);
    }
    const formattedDisplayNumber = formattedNumber.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3"
    );
    setFormattedPhone(formattedDisplayNumber);
    setValue("phone", formattedDisplayNumber);
  };

  return (
    <Modal
      {...props}
      size='lg'
      aria-labelledby='contained-modal-title-vcenter'
      centered
    >
      <Modal.Header closeButton className='modal-header1'>
        <Modal.Title id='contained-modal-title-vcenter'>
          Update Customer
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <ToastContainer />
        <div className='modal-body'>
          <div className='modal_form_body'>
            <form className='row g-3' onSubmit={handleSubmit(onSubmit)}>
              <div className='col-md-6 my-2'>
                <label htmlFor='name' className='form-label'>
                  <b> Customer Name</b>
                </label>
                <Controller
                  name='customer'
                  control={control}
                  render={({ field }) => (
                    <input
                      type='text'
                      className={`form-control ${errors.customer ? "is-invalid" : ""}`}
                      id='name'
                      {...field}
                    />
                  )}
                />
                {errors.customer && (
                  <div className='invalid-feedback'>
                    {errors.customer.message}
                  </div>
                )}
              </div>
              <div className='col-md-6 my-2'>
                <label htmlFor='city' className='form-label'>
                  <b> City</b>
                </label>
                <Controller
                  name='city'
                  control={control}
                  render={({ field }) => (
                    <input
                      type='text'
                      className={`form-control ${errors.city ? "is-invalid" : ""}`}
                      id='city'
                      {...field}
                    />
                  )}
                />
                {errors.city && (
                  <div className='invalid-feedback'>{errors.city.message}</div>
                )}
              </div>
              <div className='col-md-4 my-2'>
                <label htmlFor='state' className='form-label'>
                  <b> State</b>
                </label>
                <Controller
                  name='state'
                  control={control}
                  render={({ field }) => (
                    <select
                      id='state'
                      className={`form-select ${
                        errors.state ? "is-invalid" : ""
                      }`}
                      {...field}
                    >
                      <option value={null}>---Select State---</option>
                      {filteredStates?.map((item, i) => (
                        <option key={i} value={item?.state_code}>
                          {item?.state_name}
                        </option>
                      ))}
                    </select>
                  )}
                />
                {errors.state && (
                  <div className='invalid-feedback'>{errors.state.message}</div>
                )}
              </div>
              <div className='col-md-4 my-2'>
                <label htmlFor='phone' className='form-label'>
                  <b> Phone</b>
                </label>
                {updateFunction(
                  control,
                  errors,
                  handlePhoneChange,
                  formattedPhone
                )}

                {errors.phone && (
                  <div className='invalid-feedback'>{errors.phone.message}</div>
                )}
                {phoneErrorVisible && (
                  <p className='text-danger'>
                    Phone number must have at least 0 or 10 digits.
                  </p>
                )}
              </div>
              <div className='col-md-4 my-2'>
                <label htmlFor='sales_rep' className='form-label'>
                  <b> Assigned Rep</b>
                </label>
                <Controller
                  name='sales_rep'
                  control={control}
                  render={({ field }) => (
                    <input
                      type='text'
                      className={`form-control ${errors.sales_rep ? "is-invalid" : ""}`}
                      id='sales_rep'
                      {...field}
                    />
                  )}
                />
                {errors.sales_rep && (
                  <div className='invalid-feedback'>
                    {errors.sales_rep.message}
                  </div>
                )}
              </div>
              <div className='col-md-6 my-2'>
                <label htmlFor='contact' className='form-label'>
                  <b> Contact Name</b>
                </label>
                <Controller
                  name='contact'
                  control={control}
                  render={({ field }) => (
                    <input
                      type='text'
                      className={`form-control ${errors.contact ? "is-invalid" : ""}`}
                      id='contact'
                      {...field}
                    />
                  )}
                />
                {errors.contact && (
                  <div className='invalid-feedback'>
                    {errors.contact.message}
                  </div>
                )}
              </div>
              <div className='col-md-6 my-2'>
                <label htmlFor='email' className='form-label'>
                  <b> Draydex Email</b>
                </label>
                <Controller
                  name='email'
                  control={control}
                  a
                  render={({ field }) => (
                    <input
                      type='email'
                      className={`form-control ${
                        errors.email ? "is-invalid" : ""
                      }`}
                      id='email'
                      {...field}
                    />
                  )}
                />
                {draydexemail && (
                  <p className='text-danger'>
                    DrayDex email is required when add to sent rates is "Yes"
                  </p>
                )}

                {errors.email && (
                  <div className='invalid-feedback'>{errors.email.message}</div>
                )}
              </div>
              <div className='radio_btn'>
              <div className='modal-footer1 d-flex justify-content-center alin-items-center gap-3' style={{marginTop: "26px"}}>
                <button type='submit' className='btn btn-submit divStylecss-update'>
                  Submit
                </button>
                <div onClick={handleCancel} className='btn btn-cancel divStylecss-update'>
                  Cancel
                </div>
              </div>
                <div className='form-check'>
                  <label className='form-label'>
                    <b>Add to Sent Rates?</b>
                  </label>
                  <div className='badge_block popup_btn'>
                    <div className='float-right'>
                      <Controller
                        name='is_sent_rate'
                        control={control}
                        render={({ field }) => (
                          <div>
                            <input
                              type='radio'
                              autoComplete='off'
                              id='option-lbs'
                              className={`btn-check form-control ${errors.is_sent_rate ? "is-invalid" : ""}`}
                              value='1'
                              checked={field.value === "1"}
                              onChange={() => field.onChange("1")}
                            />
                            <label
                              className='btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light mb-0 form-label'
                              htmlFor='option-lbs'
                            >
                              Yes
                            </label>
                          </div>
                        )}
                      />
                    </div>
                    <span className='span-cross-rate'>/</span>
                    <div>
                      <Controller
                        name='is_sent_rate'
                        control={control}
                        render={({ field }) => (
                          <div>
                            <input
                              type='radio'
                              autoComplete='off'
                              id='option-kg'
                              className={`btn-check form-control ${errors.is_sent_rate ? "is-invalid" : ""}`}
                              value='0'
                              checked={field.value === "0"}
                              onChange={() => field.onChange("0")}
                            />
                            <label
                              className='btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light mb-0 form-label'
                              htmlFor='option-kg'
                            >
                              No
                            </label>
                          </div>
                        )}
                      />
                    </div>
                  </div>
                </div>
              </div>
              
            </form>
          </div>
        </div>
      </Modal.Body>
    </Modal>
  );
}

function MyVerticallyCenteredModal(props: any) {
  const [formattedPhone, setFormattedPhone] = useState(null);
  const [selectedItems, setSelectedItems] = useState([]);
  const [phoneErrorVisible, setPhoneErrorVisible] = useState(false);
  const [info, setInfo] = useState();
  const infoChild = props?.child?.setListingRef;
  const isSent = info?.is_sent_rate == "YES" ? "1" : "0";
  const {
    handleSubmit,
    control,
    reset,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });
  const fetch = async () => {
    if(props?.id?.userdata?.id){
      let id = {
        user_id: props?.id?.userdata?.id,
      };
      let res = await GetAccociateDetails(token, id);
  
      setInfo(res?.data);
    }
  };
  useEffect(() => {
    fetch();
  }, [props?.show]);

  const handleCheckboxChange = (itemName) => {
    const isSelected = selectedItems.includes(itemName);
    if (isSelected) {
      setSelectedItems(selectedItems.filter((item) => item !== itemName));
    } else {
      setSelectedItems([...selectedItems, itemName]);
    }
  };

  useEffect(() => {
    const formattedBillingPhone = info?.phone
      ? info?.phone
          .replace(/\D/g, "")
          .replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
      : "";
    const formattedDisplayNumberWithoutHyphens = formattedBillingPhone.replace(
      /-/g,
      ""
    );
    const formattedDisplayNumberAsNumber = parseInt(
      formattedDisplayNumberWithoutHyphens,
      10
    );
    const formattedPhoneNumber = formattedBillingPhone.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3"
    );

    setValue("name", info?.name === null ? "N/A" : info?.name);
    setValue("username", info?.username);
    setValue("status", info?.is_active === 1 ? "1" : "0");
    setValue("email", info?.email);
    setValue("role_label", info?.permission_base_role);
    setValue("is_sent_rate", isSent);

    setValue(
      "phone",
      formattedPhoneNumber !== null ? formattedDisplayNumberAsNumber : null
    );

    setFormattedPhone(
      formattedPhoneNumber !== null ? formattedPhoneNumber : "N/A"
    );
  }, [info, isSent, props]);
  const { data } = useSession();
  const token = data?.user?.image;

  useEffect(() => {
    if (info && info.permissions) {
      const initialSelectedItems = Object.values(info.permissions).flatMap(
        (category) =>
          category
            .filter((item) => item.is_selected === 1)
            .map((item) => item.name)
      );
      setSelectedItems(initialSelectedItems);
    }
  }, [info]);
  const [selectAll, setSelectAll] = useState({});

  const onSubmit = async (data1: {
    is_sent_rate: string;
    email: string | any[];
  }) => {
    toast.dismiss();
    if (
      data1?.is_sent_rate === "1" &&
      (!data1?.email || data1?.email.length === 0)
    ) {
      return;
    } else {
      let uniqueSelectedItems = [...new Set(selectedItems)];
      if (!phoneErrorVisible) {
        let payload = {
          user_id: props?.id?.userdata?.id,
          permissions: uniqueSelectedItems,
          name: data1?.name,
          phone: data1?.phone,
          status: data1?.status,
        };

        const response = await AssociateChildUpdate(token, payload);

        if (response.status === "success") {
          setShowList([]);
          setSelectAll([]);
          infoChild(true);

          reset();
          toast.success(response.message, {
            position: toast.POSITION.TOP_CENTER,
          });
          fetch();
          props.onHide();
        } else {
          toast.error(response.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      }
    }
  };

  const handleCancel = () => {
    setPhoneErrorVisible(false);
    props.onHide();
    setShowList([]);
    setSelectAll([]);
    reset();
  };
  const handlePhoneChange = (event: { target: { value: any } }) => {
    let inputValue = event.target.value;
    const cleanedInput = inputValue.replace(/\D/g, "");
    const formattedNumber = cleanedInput.slice(0, 10);
    if (formattedNumber.length >= 1 && formattedNumber.length <= 9) {
      setPhoneErrorVisible(true);
    } else {
      setPhoneErrorVisible(false);
    }
    const formattedDisplayNumber = formattedNumber.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3"
    );
    const formattedDisplayNumberWithoutHyphens = formattedDisplayNumber.replace(
      /-/g,
      ""
    );
    const formattedDisplayNumberAsNumber = parseInt(
      formattedDisplayNumberWithoutHyphens,
      10
    );
    setFormattedPhone(formattedDisplayNumber);
    setValue("phone", formattedDisplayNumberAsNumber);
  };
  const sortedEntries = info?.permissions
    ? Object.entries(info.permissions).sort(([keyA], [keyB]) => {
        if (keyA === "Premium;") return 1;
        if (keyB === "Premium") return -1;
        return 0;
      })
    : [];
  const handleSelectAll = (items, key) => {
    const allSelected = items.every((item) =>
      selectedItems.includes(item.name)
    );
    let updatedSelectedItems = [];

    if (!allSelected) {
      updatedSelectedItems = [
        ...selectedItems,
        ...items.map((item) => item.name),
      ];
    } else {
      updatedSelectedItems = selectedItems.filter(
        (selectedItem) => !items.map((item) => item.name).includes(selectedItem)
      );
    }

    setSelectedItems(updatedSelectedItems);

    setSelectAll({ ...selectAll, [key]: !allSelected });
  };

  const [showList, setShowList] = useState({});
  const toggleList = (key) => {
    setShowList({ ...showList, [key]: !showList[key] });
  };
  const [pop, setPop] = useState(false);

  const makeAdmin = () => {
    setPop(!pop);
  };
  const [disabled,setDisabled]= useState(false)
  const makeAdminCall = async () => {
    setDisabled(true);
    let payload = {
      client_id: props?.child?.rowData?.parent_id,
      child_id: props?.child?.rowData?.id,
    };
    let res = await adminUser(payload, token);
    if (res?.status === "success") {
      toast.success(res.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      setDisabled(false);
      setPhoneErrorVisible(false);
      props.onHide();
      setShowList([]);
      setSelectAll([]);
      reset();
      setPop(false);
      props?.child?.setRefresh(true)
    }
    
  
  };
  const classpop = pop ?"second__modal modal-dialog-centered":""
  return (
    <Modal
      {...props}
      size='lg'
      aria-labelledby='contained-modal-title-vcenter'
      centered
    >
      <Modal.Header closeButton className='modal-header1'>
        <div className="table-headers h3 ">
        <h3 style={{ color: "#3180f3" }} id='contained-modal-title-vcenter'>
          Associated User Details
        </h3>
        </div>
      </Modal.Header>
      <Modal.Body>
        <ToastContainer />
        <div className='modal-body'>
          <div className='modal_form_body'>
            <form className='row g-3' onSubmit={handleSubmit(onSubmit)}>
              <div className='col-md-5 my-2'>
                <label htmlFor='name' className='form-label'>
                  <b> Name</b>
                </label>
                <Controller
                  name='name'
                  control={control}
                  render={({ field }) => (
                    <input
                      type='text'
                      className={`form-control ${errors.name ? "is-invalid" : ""}`}
                      id='name'
                      {...field}
                    />
                  )}
                />
                {errors.name && (
                  <div className='invalid-feedback'>{errors.name.message}</div>
                )}
              </div>
              <div className='col-md-4 my-2'>
                <label htmlFor='username' className='form-label'>
                  <b>Login Username</b>
                </label>
                <Controller
                  name='username'
                  control={control}
                  render={({ field }) => (
                    <input
                      disabled={true}
                      type='text'
                      className={`form-control ${errors.username ? "is-invalid" : ""}`}
                      id='username'
                      {...field}
                    />
                  )}
                />
                {errors.username && (
                  <div className='invalid-feedback'>
                    {errors.username.message}
                  </div>
                )}
              </div>
              <div className='col-md-3 my-2'>
                <label htmlFor='status' className='form-label'>
                  <b>Status</b>
                </label>
                <div>
                  <Controller
                    name='status'
                    control={control}
                    render={({ field }) => (
                      <FormControl
                        as='select'
                        id='status_active'
                        className={`form-select ${
                          errors.status ? "is-invalid" : ""
                        }`}
                        {...field}
                      >
                        <option value=''>Select Status</option>
                        <>
                          <option value='1'>Active</option>
                          <option value='0'>Inactive</option>
                        </>
                        );
                      </FormControl>
                    )}
                  />
                </div>
                {errors.status && (
                  <div className='invalid-feedback'>
                    {errors.status.message}
                  </div>
                )}
              </div>

              <div className='col-md-4 my-2'>
                <label htmlFor='phones' className='form-label'>
                  <b> Phone</b>
                </label>
                {updateFunction(
                  control,
                  errors,
                  handlePhoneChange,
                  formattedPhone
                )}
                {errors.phone && (
                  <div className='invalid-feedback'>{errors.phone.message}</div>
                )}
                {phoneErrorVisible && (
                  <p className='text-danger'>
                    Phone number must have at least 0 or 10 digits.
                  </p>
                )}
              </div>
              <div className='col-md-5 my-2'>
                <label htmlFor='email' className='form-label'>
                  <b>Email</b>
                </label>
                <Controller
                  name='email'
                  control={control}
                  render={({ field }) => (
                    <input
                      disabled={true}
                      type='text'
                      className={`form-control ${errors.email ? "is-invalid" : ""}`}
                      id='email'
                      {...field}
                    />
                  )}
                />
                {errors.email && (
                  <div className='invalid-feedback'>{errors.email.message}</div>
                )}
              </div>
              <div className='col-md-3 my-2'>
                <label htmlFor='role_label' className='form-label'>
                  <b>User Role</b>
                </label>
                <Controller
                  name='role_label'
                  control={control}
                  render={({ field }) => (
                    <input
                      disabled={true}
                      type='text'
                      className={`form-control ${errors.role_label ? "is-invalid" : ""}`}
                      id='role_label'
                      {...field}
                    />
                  )}
                />
                {errors.role_label && (
                  <div className='invalid-feedback'>
                    {errors.role_label.message}
                  </div>
                )}
              </div>
              <div className='col-md-12 my-2'>
                <h5 className='advance_heading'>Advance</h5>
              </div>
              {sortedEntries.map(([key, value]) => {
                const anySelected = value.some((item) =>
                  selectedItems.includes(item?.name)
                );
                return (
                  <div
                    key={key}
                    className={
                      key === "Premium" ? "col-md-12 my-2" : "col-md-6 my-2"
                    }
                  >
                    <div
                      className={key === "Premium" ? "" : "check_name"}
                      style={key === "Premium" ? { border: "none" } : {}}
                    >
                      {key !== "Premium" && (
                        <div className='form-check  check_block'>
                          <input
                            checked={selectAll[key] || anySelected}
                            className='form-check-input check_border'
                            type='checkbox'
                            value=''
                            id={`selectAll${key}`}
                            onChange={() => handleSelectAll(value, key)}
                          />
                        </div>
                      )}
                      <h5
                        className={` ${key === "Premium" ? "advance_heading" : "label_name"}`}
                        style={key === "Premium" ? { border: "none" } : {}}
                      >
                        {key}
                      </h5>
                      {key === "Premium" ? null : (
                        <button
                          onClick={() => toggleList(key)}
                          className='btn_check_toggle dropdown-toggle'
                          type='button'
                          data-mdb-dropdown-init
                          data-mdb-ripple-init
                          aria-expanded='false'
                        ></button>
                      )}
                    </div>
                    {(key === "Premium" || showList[key]) && (
                      <div>
                        {value?.map((item, index) => (
                          <div
                            style={
                              key === "Premium" ? { marginTop: "10px" } : {}
                            }
                            className='form-check sub_check'
                          >
                            <input
                              style={{ position: "absolute" }}
                              checked={selectedItems?.includes(item?.name)}
                              className='form-check-input check_border'
                              type='checkbox'
                              value=''
                              id={`flexCheckDefault${index}`}
                              disabled={key === "Premium"}
                              onChange={() =>
                                handleCheckboxChange(item?.name, key)
                              }
                            />
                            <label
                              className='form-check-label'
                              htmlFor={`flexCheckDefault${index}`}
                            >
                              {item?.name}
                            </label>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
              <div>
                {data?.user?.group_type === "super_admin" ? <div className='form-check sub_check'>
                  <input
                    style={{ position: "absolute" }}
                    checked={pop}
                    onClick={() => makeAdmin()}
                    className='form-check-input check_border'
                    type='checkbox'
                    value=''
                  />
                  <label className='form-check-label'>Make Admin User</label>
                </div>:""}
              

                {/* ))} */}
              </div>
            
              

              <div className='modal-footer1 d-flex justify-content-center alin-items-center gap-3'>
                <button
                  disabled={
                    props?.id?.userdata?.rowData?.is_email_verified !== 1
                      ? true
                      : false
                  }
                  type='submit'
                  className='btn btn-submit'
                >
                  Submit
                </button>
                <div onClick={handleCancel} className='btn btn-cancel'>
                  Cancel
                </div>
              </div>
            </form>
          </div>
        </div>
      </Modal.Body>
      
      <div className={classpop}>
        <Modal show={pop} onHide={pop} backdrop='static'>
          <Modal.Header>
            <h5>Update Admin User permission</h5>
          </Modal.Header>
          <Modal.Header>
            <Modal.Title>
              Are you sure you want to make this <br /> user the Admin User
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className='reg_button'>
              <Button
                variant='secondary'
                onClick={() => makeAdmin()}
                className='mx-2 carrierButton'
              >
                No
              </Button>
              <Button
                disabled={disabled}
                variant='danger'
                className='mx-2 customerButton'
                onClick={() => makeAdminCall()}
              >
                Yes
              </Button>
            </div>
          </Modal.Body>

        </Modal>
      </div>
    </Modal>
  );
}

function updateFunction(
  control,
  errors,
  handlePhoneChange: (event: { target: { value: any } }) => void,
  formattedPhone: null
) {
  return (
    <Controller
      name='phone'
      control={control}
      render={({ field }) => (
        <input
          type='text'
          className={`form-control ${errors.phone ? "is-invalid" : ""}`}
          id='phone'
          {...field}
          onChange={handlePhoneChange}
          value={formattedPhone}
        />
      )}
    />
  );
}

export default function UpdateCustomer(props: any) {  
  const [modalShow, setModalShow] = React.useState(false);
  const [modalDisplay, setModalDisplay] = React.useState(false);
  const { data } = useSession();
  const handleClick = () => {
    setModalShow(true);
  };
  let buttonComponent;

  if (props?.userdata?.modal) {
    buttonComponent = (
      <button
        className='updateBtnCss'
        onClick={() => {
          setModalDisplay(true);
        }}
      >
        <i className='bi bi-pencil-square'></i>
      </button>
    );
  } else if (props?.userdata?.status === true) {
    const renderTooltip = (prop) => (
      <Tooltip id="button-tooltip" {...prop}>
        Users for unclaimed carriers cannot be edited.
      </Tooltip>
    );


    const isSuperAdmin = data?.user?.group_type === "super_admin";
    const isParentNull = props?.userdata?.rowData?.parent_id === null;
    const hasDetailingCondition = props?.userdata?.values?.DetailingCondition;
    const isCarrier = props?.userdata?.values?.propData?.data?.user_type === "carrier";

    if (isSuperAdmin && isParentNull) {
      if (hasDetailingCondition && isCarrier) {
        buttonComponent = (
          <OverlayTrigger
            placement="top"
            delay={{ show: 250, hide: 400 }}
            overlay={renderTooltip}
          >
            <button className='updateBtnCss'>
              <i className='bi bi-pencil-square pencil-square1'></i>
            </button>
          </OverlayTrigger>
        );
      } else {
        buttonComponent = (
          <button className='updateBtnCss'>
            <i className='bi bi-pencil-square pencil-square1'></i>
          </button>
        );
      }
    } else {
      buttonComponent = (
        <button className='updateBtnCss' onClick={handleClick}>
          <i className='bi bi-pencil-square'></i>
        </button>
      );
    }
  }


  else {
    buttonComponent = (
      <a
        href={`/users/${props?.userdata?.rowData?.user_id}?type=${props?.userdata?.rowData?.user_type}`}
        className='updateBtnCss'
        style={{ backgroundColor: "white" }}
      >
        <i className='bi bi-pencil-square'></i>
      </a>
    );
  }
  return (
    <>
      {buttonComponent}
      <MyVerticallyCenteredModal
        show={modalShow}
        onHide={() => setModalShow(false)}
        child={props?.userdata}
        id={props}
      />
      <MyVerticallyCenteredModals
        show={modalDisplay}
        onHide={() => setModalDisplay(false)}
        child={props?.userdata}
      />
    </>
  );
}
