import {
  getCarrierparsonalDetails,
  carrierparsonalDetailsUpdate,
} from "@/services/profile";
import { useSession } from "next-auth/react";
import { ToastContainer, toast } from "react-toastify";
import { Form, FormGroup, FormLabel, FormControl } from "react-bootstrap";
import { ScaleLoader } from "react-spinners";
import { useUser } from "@/components/Context/UserContext";
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string } from "yup";
import Image from "next/image";
import {
  mapboxAddressActionUrl,
  replaceCapitalLettersAndUnderscores,
} from "@/helpers/projectHelper";
import { toUnsubscribeEmail } from "@/services/public";
import useAuthProvider from "@/useAuthProvider";
interface FormData {
  company_name: string;
  billing_address: string;
  current_address: string;
  phone_number: number;
  currentpassword: any;
  confirmpassword: any;
  newpassword: any;
  firstName: string;
  lastName: string;
  business_email: string;
  is_subscribed_status: number;
}

function CarrierPersonalDetails() {
  const { data } = useSession();

  const { Permission: userData } = useAuthProvider();

  let schema = object().shape({
    firstName: string()
      .required("First name is required")
      .min(2, "Minimum 2 characters required")
      .max(20, "Maximum 20 characters allowed"),
    lastName: string()
      .required("Last name is required")
      .min(2, "Minimum 2 characters required")
      .max(20, "Maximum 20 characters allowed"),
    company_name: string()
      .required("Company name is required")
      .min(2, "Company name must be at least 2 characters")
      .max(100, "Company name cannot exceed 100 characters"),
      phone_number: string()
      .required("Phone number is required")
      .test(
        "len",
        "Phone number must be 10 digits",
        (val) => {
          const cleaned = val.replace(/\D/g, "");
          return cleaned.length === 10; // Check for 10 or 11 digits
        }
      ),
    
    currentpassword: string().test({
      name: "currentpassword",
      message: "New password is required",
      test: function (value) {
        const newpassword = this.parent.newpassword;
        return newpassword ? !!value : true;
      },
    }),
    newpassword: string().test({
      name: "newpassword",
      message: "New password is required",
      test: function (value) {
        const currentPassword = this.parent.currentpassword;
        return currentPassword ? !!value : true;
      }
    }),
    confirmpassword: string().test(
      "passwords-match",
      "The passwords do not match",
      function (value) {
        return this.parent.newpassword === value;
      }
    ),
  });

  schema = jsxContectMid(data, schema);
  const [isloading, setIsloading] = useState(true);
  const token = data?.user?.image;
  const carrierId = data?.user?.carrier_id;
  const [customeAddressError, setCustomeAddressError] = useState("");
  const [selectedOriginDestination, setSelectedOriginDestination] =
    useState("");
  const [selectedbillingDestination, setselectedbillingDestination] =
    useState("");
  const [searchedSuggestions, setSearchSuggestions] = useState([]);
  const [searchedbillingSuggestions, setSearchbillingSuggestions] = useState(
    []
  );
  const [MapState, setMapState] = useState();
  const [MapCity, setMapCity] = useState();
  const { updateUserName, updatelastName } = useUser();
  const [buttonDisable, setButtonDisable] = useState(false);
  const [firstname, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [companyName, setcompanyName] = useState("");
  const [businessEmail, setbusinessEmail] = useState("");
  const [number, setNumber] = useState("");
  const [checked, setChecked] = useState(false);
  const [isSubscribeStatus, setSubscribeStatus] = useState(0);

  const [showPassword, setShowPassword] = useState(false);
  const [showNewPassword, setNewShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [carrierusername, setCarrierUsername] = useState("");
  const setFieldValueAndState = (
    field: string,
    stateSetter: (value: string) => void
  ) => {
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      setValue(field, value);
      stateSetter(value);
    };
  };

  function capitalizeFirstLetter(item: string) {
    return item?.charAt(0)?.toUpperCase() + item?.slice(1)?.toLowerCase();
  }

  function numberformat(phoneNumberString: string) {
    const phoneNumberParts = phoneNumberString.split("-");
    return parseInt(
      phoneNumberParts[0] + phoneNumberParts[1] + phoneNumberParts[2]
    );
  }

  const handleFieldChange = (
    field: string,
    stateSetter: (value: string) => void
  ) => {
    return {
      onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
        onKeyDownScope(e);
      },
      placeholder: replaceCapitalLettersAndUnderscores(field),
      type: "text",
      value: getFieldState(field),
      className: onKeyDownClass(errors, field),
      id: field,
      ...register(field, {
        onChange: setFieldValueAndState(field, stateSetter),
      }),
    };
  };

  const getFieldState = (field: string) => {
    return SwitchScope(
      field,
      firstname,
      lastName,
      businessEmail,
      number,
      companyName
    );
  };

  function formatPhoneNumber(input) {
    const cleaned = input?.replace(/\D/g, "");
  
    if (cleaned.length === 10) {
      return cleaned?.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
    }
  
    return input;
  }

  const spaceblockhandler = (event) => {
    blockHandler(event);
  };

  const {
    handleSubmit,
    setValue,
    register,
    formState: { errors },
  } = useForm<FormData>({
    resolver: yupResolver(schema),
  });
  useEffect(() => {
    EffectScopeHandler(
      { token, carrierId, setIsloading, setValue, capitalizeFirstLetter, setMapCity, setMapState, data, formatPhoneNumber, setNumber, setSubscribeStatus, setFirstName, setLastName, setbusinessEmail, setCarrierUsername, setselectedbillingDestination, setSelectedOriginDestination, setcompanyName });
  }, [isloading]);

  const spacehandler = (event) => {
    if (event.which === 32 && event.target.value.trim() === "") {
      event.preventDefault();
    }
  };

  function bindSelectedAddress(item: SelectAddressType) {
    setValue("current_address", item.name);
    setSearchSuggestions([]);
    setSelectedOriginDestination(item.name);
    setCustomeAddressError("");
  }

  function bindbillingSelectedAddress(item: SelectAddressType) {
    setValue("billing_address", item.name);
    setSearchbillingSuggestions([]);
    setselectedbillingDestination(item.name);
    setCustomeAddressError("");
  }

  const handleAddressChange = async (
    event: React.ChangeEvent<HTMLInputElement>,
    setAddressValue: (value: string) => void,
    setSuggestions: (suggestions: any[]) => void
  ) => {
    await AddressChangeScope32(event, setSuggestions);
  };
  const getHideClass = () => {
    return searchedbillingSuggestions.length < 1 ? "d-none" : "";
  };
  const sameAddressHandler = (e) => {
    sameAddressHandlerScopeL(
      setChecked,
      e,
      checked,
      setselectedbillingDestination,
      setValue,
      selectedOriginDestination
    );
  };

  const handleUnsubcribeStatus = (unsubscribeDataStatus: any) => {
    handleUnsubcribeStatusScopeL(
      unsubscribeDataStatus,
      setSubscribeStatus,
      toUpdateUnsubscribeStatus
    );
  };

  const toUpdateUnsubscribeStatus = (dataVal: any) => {
    toUpdateUnsubscribeStatusScope(dataVal, token);
  };

  const RenderTemplate = () => {
    return RenderTemplateScopeL(
      { isloading, handleSubmit, onSubmit, spaceblockhandler, handleFieldChange, setFirstName, errors, setLastName, setbusinessEmail, data, isSubscribeStatus, handleUnsubcribeStatus, carrierusername, formatPhoneNumber, number, setNumber, register, setcompanyName, selectedOriginDestination, customeAddressError, spacehandler, handleAddressChange, setSelectedOriginDestination, setSearchSuggestions, searchedSuggestions, bindSelectedAddress, setMapState, setMapCity, checked, sameAddressHandler, selectedbillingDestination, setselectedbillingDestination, setSearchbillingSuggestions, setCustomeAddressError, getHideClass, searchedbillingSuggestions, bindbillingSelectedAddress, showPassword, setShowPassword, showNewPassword, setNewShowPassword, showConfirmPassword, setShowConfirmPassword, userData, buttonDisable });
  };
  const onSubmit = async (FormData: any) => {
    await onSubmitHook(
      { setButtonDisable, setIsloading, token, carrierId, FormData, data, numberformat, MapState, MapCity, isSubscribeStatus, updateUserName, updatelastName, setValue }    );
  };
  return <>{RenderTemplate()}</>;
}

export default CarrierPersonalDetails;

interface PropTypes {
  type?: string;
  id: string;
  placeHolder: string;
  register: any;
  errors: any;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void; // Add this line
}

interface CustomPropType extends PropTypes {
  state: boolean;
}

function onKeyDownClass(errors, field: string) {
  return `form-control ${errors[field] ? "is-invalid" : ""}`;
}

function onKeyDownScope(e: React.KeyboardEvent<HTMLInputElement>) {
  if (e.which === 32 && e.target.value.trim() === "") {
    e.preventDefault();
  }
}

function jsxContectMid(data, schema) {
  if (data?.user?.role_id !== 3 && data?.user?.role_id !== 5) {
    schema = schema.shape({
      current_address: string()
        .required("Current address is required")
        .min(2, "Minimum 2 characters required")
        .max(200, "Maximum 200 characters allowed"),
    });
  }
  return schema;
}

async function onSubmitHook(
{ setButtonDisable, setIsloading, token, carrierId, FormData, data, numberformat, MapState, MapCity, isSubscribeStatus, updateUserName, updatelastName, setValue }: { setButtonDisable: React.Dispatch<React.SetStateAction<boolean>>; setIsloading: React.Dispatch<React.SetStateAction<boolean>>; token: any; carrierId: any; FormData: any; data; numberformat: (phoneNumberString: string) => number; MapState: undefined; MapCity: undefined; isSubscribeStatus: number; updateUserName: any; updatelastName: any; setValue; }) {
  setButtonDisable(true);
  setIsloading(true);
  const response = await carrierparsonalDetailsUpdate(token, carrierId, {
    first_name: FormData.firstName,
    last_name: FormData.lastName,
    company_name: FormData.company_name,
    email: FormData.business_email,
    current_address: FormData.current_address,
    billing_address: billingScope1(data, FormData),
    phone: numberformat(FormData.phone_number),
    state: MapState,
    city: MapCity,
    current_password: FormData.currentpassword,
    new_password: FormData.newpassword,
    is_subscribed: isSubscribeStatus,
  });
  updateUserName(FormData.firstName);
  updatelastName(FormData.lastName);
  SubmitScopeCondition(response, setButtonDisable, setIsloading, setValue);
}

function RenderTemplateScopeL(
  { isloading, handleSubmit, onSubmit, spaceblockhandler, handleFieldChange, setFirstName, errors, setLastName, setbusinessEmail, data, isSubscribeStatus, handleUnsubcribeStatus, carrierusername, formatPhoneNumber, number, setNumber, register, setcompanyName, selectedOriginDestination, customeAddressError, spacehandler, handleAddressChange, setSelectedOriginDestination, setSearchSuggestions, searchedSuggestions, bindSelectedAddress, setMapState, setMapCity, checked, sameAddressHandler, selectedbillingDestination, setselectedbillingDestination, setSearchbillingSuggestions, setCustomeAddressError, getHideClass, searchedbillingSuggestions, bindbillingSelectedAddress, showPassword, setShowPassword, showNewPassword, setNewShowPassword, showConfirmPassword, setShowConfirmPassword, userData, buttonDisable }: {
    isloading: boolean; handleSubmit; onSubmit: (FormData: any) => Promise<void>; spaceblockhandler: (event: any) => void; handleFieldChange; setFirstName: React.Dispatch<React.SetStateAction<string>>; errors; setLastName: React.Dispatch<React.SetStateAction<string>>; setbusinessEmail: React.Dispatch<React.SetStateAction<string>>; data; isSubscribeStatus: number; handleUnsubcribeStatus: (unsubscribeDataStatus: any) => void; carrierusername: string; formatPhoneNumber: (input: any) => any; number: string; setNumber: React.Dispatch<React.SetStateAction<string>>; register; setcompanyName: React.Dispatch<React.SetStateAction<string>>; selectedOriginDestination: string; customeAddressError: string; spacehandler: (event: any) => void; handleAddressChange: (
      event: React.ChangeEvent<HTMLInputElement>,
      setAddressValue: (value: string) => void,
      setSuggestions: (suggestions: any[]) => void
    ) => Promise<void>; setSelectedOriginDestination: React.Dispatch<React.SetStateAction<string>>; setSearchSuggestions: React.Dispatch<React.SetStateAction<never[]>>; searchedSuggestions: never[]; bindSelectedAddress: (item: SelectAddressType) => void; setMapState: React.Dispatch<React.SetStateAction<undefined>>; setMapCity: React.Dispatch<React.SetStateAction<undefined>>; checked: boolean; sameAddressHandler: (e: any) => void; selectedbillingDestination: string; setselectedbillingDestination: React.Dispatch<React.SetStateAction<string>>; setSearchbillingSuggestions: React.Dispatch<React.SetStateAction<never[]>>; setCustomeAddressError: React.Dispatch<React.SetStateAction<string>>; getHideClass: () => "" | "d-none"; searchedbillingSuggestions: never[]; bindbillingSelectedAddress: (item: SelectAddressType) => void; showPassword: boolean; setShowPassword: React.Dispatch<React.SetStateAction<boolean>>; showNewPassword: boolean; setNewShowPassword: React.Dispatch<React.SetStateAction<boolean>>; showConfirmPassword: boolean; setShowConfirmPassword: React.Dispatch<React.SetStateAction<boolean>>; userData: undefined; buttonDisable: boolean;
  }) {
  return (
    <>
      <div>
        {isloading && (
          <div id='loader_table'>
            <ScaleLoader color='#3180f3' className='table_loader' />
          </div>
        )}
        <ToastContainer />
        <div
          className='tab-pane fade show active'
          id='pills-home'
          role='tabpanel'
          aria-labelledby='pills-home-tab'
        >
          <div className='tab_content'>
            <div className='edit_btn_block '>
              <i
                className='fa fa-pencil-square-o'
                aria-hidden='true'
                title='Edit fields'
              />
            </div>
            <form className='row g-4' onSubmit={handleSubmit(onSubmit)}>
              <div className='col-md-4 mb-3'>
                <FormLabel htmlFor='firstName'>First Name:</FormLabel>
                <FormControl
                  onKeyPress={spaceblockhandler}
                  {...handleFieldChange("firstName", setFirstName)}
                />
                <p className='text-danger'>{errors?.firstName?.message}</p>
              </div>
              <div className='col-md-4 mb-3'>
                <FormLabel htmlFor='lastName'>Last Name:</FormLabel>
                <FormControl
                  onKeyPress={spaceblockhandler}
                  {...handleFieldChange("lastName", setLastName)}
                />
                <p className='text-danger'>{errors?.lastName?.message}</p>
              </div>

              <div className='col-md-4 mb-3  '>
                <FormLabel htmlFor='business_email'>Email:</FormLabel>
                <FormControl
                  disabled
                  readOnly
                  {...handleFieldChange("business_email", setbusinessEmail)}
                />
                <p className='text-danger'>{errors?.business_email?.message}</p>
                {data?.user?.group_type === "carriers" &&
                  data?.user?.role_id !== 3 &&
                  data?.user?.role_id !== 5 && (
                    <div>
                      <input
                        type='checkbox'
                        className='form-check-input'
                        checked={isSubscribeStatus}
                        onChange={(e) =>
                          handleUnsubcribeStatus(isSubscribeStatus)
                        }
                      />
                      &nbsp;I want to receive the rate emails from Draydex
                    </div>
                  )}
              </div>
              <div className='col-md-4 mb-3  '>
                <FormLabel htmlFor='username'>Username:</FormLabel>
                <FormControl
                  disabled
                  type='text'
                  id={"username"}
                  value={carrierusername}
                  placeholder='Username'
                />
              </div>
              <div className='col-md-4 mb-3' style={{ display: "grid" }}>
                <FormLabel htmlFor='Phone number'>Phone Number:</FormLabel>
                <FormControl
                  disabled={
                    data?.user?.role_id === 3 || data?.user?.role_id === 5
                      ? true
                      : false
                  }
                  value={formatPhoneNumber(number)}
                  {...handleFieldChange("phone_number", setNumber)}
                  mask='999-999-9999'
                  placeholder='xxx-xxx-xxxx'
                  {...register("phone_number")}
                  className={errors.phone_number && "is-invalid"}
                />
                <p className='text-danger'>{errors?.phone_number?.message}</p>
              </div>
              <div className='col-md-4 mb-3  '>
                <FormLabel htmlFor='company_name'>Company Name:</FormLabel>
                <FormControl
                  disabled={
                    data?.user?.role_id === 3 || data?.user?.role_id === 5
                      ? true
                      : false
                  }
                  {...handleFieldChange("company_name", setcompanyName)}
                />
                <p className='text-danger'>{errors?.company_name?.message}</p>
              </div>

              <div className='col-md-4 mb-3  '>
                <FormLabel htmlFor='current_address'>
                  Current Address:
                </FormLabel>
                <div className='address-autocomplete-parent'>
                  <FormControl
                    disabled={
                      data?.user?.role_id === 3 || data?.user?.role_id === 5
                        ? true
                        : false
                    }
                    {...register("current_address")}
                    className={
                      ((selectedOriginDestination === "" &&
                        errors.current_address) ||
                        customeAddressError) &&
                      "is-invalid"
                    }
                    onKeyDown={spacehandler}
                    id='origin_destination'
                    placeholder='Current address'
                    autoComplete='off'
                    onInput={(e) => {
                      e.preventDefault();
                      handleAddressChange(
                        e,
                        (value) => setSelectedOriginDestination(value),
                        setSearchSuggestions
                      );
                    }}
                    value={selectedOriginDestination}
                    onChange={(e) =>
                      setSelectedOriginDestination(e.target.value)
                    }
                  />
                  <div className={searchSujjestionScope(searchedSuggestions)}>
                    <ul className='city-listing-css' style={{ zIndex: 99 }}>
                      {searchedSuggestions.map((item: any) => (
                        <li
                          key={item.name}
                          onKeyDown={spacehandler}
                          onClick={() => {
                            bindSelectedAddress({
                              name: item.name,
                              lat: item.lat,
                              lng: item.lng,
                              state_code: item.state_code,
                              post_code: item.post_code,
                            });
                            setMapState(item.state);
                            setMapCity(item.city);
                            setSelectedOriginDestination(item.name);
                          }}
                        >
                          <div className='mb-3'>{item?.name}</div>
                        </li>
                      ))}
                    </ul>
                  </div>
                  <Form.Control.Feedback type='invalid'>
                    {originScope12(
                      selectedOriginDestination,
                      errors,
                      customeAddressError
                    )}
                  </Form.Control.Feedback>
                </div>
              </div>
              {jsxBtwContent(
                { data, checked, spacehandler, sameAddressHandler, register, selectedbillingDestination, errors, customeAddressError, handleAddressChange, setselectedbillingDestination, setSearchbillingSuggestions, setCustomeAddressError, getHideClass, searchedbillingSuggestions, bindbillingSelectedAddress })}
              <div className='col-md-4 mb-3 mt-4'>
                <FormLabel htmlFor='currentpassword'>
                  Current Password:
                </FormLabel>
                <FormGroup className='form-group'>
                  <CustomFormControl
                    state={showPassword}
                    errors={errors}
                    register={register}
                    id='currentpassword'
                    placeHolder='Enter a current password'
                  />
                  <PasswordVisibilityImage
                    alt='currentpassword'
                    setState={setShowPassword}
                    state={showPassword}
                    errors={errors}
                    field='currentpassword'
                  />
                  <Form.Control.Feedback type='invalid'>
                    {errors.currentpassword?.message?.toString()}
                  </Form.Control.Feedback>
                </FormGroup>
              </div>

              <div className='col-md-4 mb-3 mt-4'>
                <FormLabel htmlFor='newpassword'>New Password:</FormLabel>
                <FormGroup className='form-group'>
                  <CustomFormControl
                    state={showNewPassword}
                    errors={errors}
                    register={register}
                    id='newpassword'
                    placeHolder='Enter a new password'
                  />
                  <PasswordVisibilityImage
                    alt='newpassword'
                    setState={setNewShowPassword}
                    state={showNewPassword}
                    errors={errors}
                    field='newpassword'
                  />
                  <Form.Control.Feedback type='invalid'>
                    {errors.newpassword?.message?.toString()}
                  </Form.Control.Feedback>
                </FormGroup>
              </div>

              <div className='col-md-4 mb-3 mt-4'>
                <FormLabel htmlFor='confirmpassword'>
                  Confirm password:
                </FormLabel>
                <FormGroup className='form-group'>
                  <CustomFormControl
                    state={showConfirmPassword}
                    errors={errors}
                    register={register}
                    id='confirmpassword'
                    placeHolder='Enter a confirm password'
                  />
                  <PasswordVisibilityImage
                    alt='confirmpassword'
                    setState={setShowConfirmPassword}
                    state={showConfirmPassword}
                    errors={errors}
                    field='confirmpassword'
                  />
                  <Form.Control.Feedback type='invalid'>
                    {errors.confirmpassword?.message?.toString()}
                  </Form.Control.Feedback>
                </FormGroup>
              </div>
              {jsxContent22(userData, buttonDisable)}
            </form>
          </div>
        </div>
      </div>
    </>
  );
}

function toUpdateUnsubscribeStatusScope(
  dataVal: any,
  token: string | null | undefined
) {
  const payloadObj = {
    is_subscribed: dataVal === 1 ? 0 : 1,
  };
  toUnsubscribeEmail(payloadObj, token);
}

function handleUnsubcribeStatusScopeL(
  unsubscribeDataStatus: any,
  setSubscribeStatus: React.Dispatch<React.SetStateAction<number>>,
  toUpdateUnsubscribeStatus: (dataVal: any) => void
) {
  if (unsubscribeDataStatus === 1) {
    setSubscribeStatus(0);
  } else {
    setSubscribeStatus(1);
  }
  toUpdateUnsubscribeStatus(unsubscribeDataStatus);
}

function sameAddressHandlerScopeL(
  setChecked: React.Dispatch<React.SetStateAction<boolean>>,
  e: any,
  checked: boolean,
  setselectedbillingDestination: React.Dispatch<React.SetStateAction<string>>,
  setValue,
  selectedOriginDestination: string
) {
  setChecked(e.target.checked);
  if (checked) {
    setselectedbillingDestination("");
    setValue("billing_address", "");
  } else {
    setValue("billing_address", selectedOriginDestination);
    setselectedbillingDestination(selectedOriginDestination);
  }
}

async function AddressChangeScope32(
  event: React.ChangeEvent<HTMLInputElement>,
  setSuggestions: (suggestions: any[]) => void
) {
  await jsxAddressChange2(event, setSuggestions);
}

async function jsxAddressChange2(event: React.ChangeEvent<HTMLInputElement>, setSuggestions: (suggestions: any[]) => void) {
  try {
    const searchedString = event.target.value;
    if (searchedString.length <= 2) {
      setSuggestions([]);
      return;
    }

    const searchResponse = await fetch(mapboxAddressActionUrl(searchedString));
    const searchedResponseData = await searchResponse.json();
    const suggestionsArray = processSearchResults(searchedResponseData.features);

    setSuggestions(suggestionsArray);
  } catch (error) {
    setSuggestions([]);
  }
}

function processSearchResults(features: any[]): any[] {
  return features.reduce((suggestions, item) => {
    const { stateCode, state, postalCode, city } = extractContextData(item.context);

    if (item?.place_type?.[0] !== "country" && stateCode !== null) {
      suggestions.push({
        name: item.place_name,
        lat: item?.center[1],
        lng: item.center[0],
        state_code: stateCode,
        state: state,
        city: city,
        post_code: postalCode,
      });
    }
    return suggestions;
  }, []);
}

function extractContextData(context: any[]): { stateCode: string | null, state: string | null, postalCode: string | null, city: string | null } {
  let stateCode = null;
  let state = null;
  let postalCode = null;
  let city = null;

  context.forEach((contextData) => {
    if (contextData.id.includes("region")) {
      stateCode = contextData.short_code;
      state = contextData.text;
    }
    if (contextData.id.includes("postcode")) {
      postalCode = contextData.text;
    }
    if (contextData.id.includes("place")) {
      city = contextData.text;
    }
  });

  return { stateCode, state, postalCode, city };
}


function EffectScopeHandler(
  { token, carrierId, setIsloading, setValue, capitalizeFirstLetter, setMapCity, setMapState, data, formatPhoneNumber, setNumber, setSubscribeStatus, setFirstName, setLastName, setbusinessEmail, setCarrierUsername, setselectedbillingDestination, setSelectedOriginDestination, setcompanyName }: { token: string | null | undefined; carrierId: any; setIsloading: React.Dispatch<React.SetStateAction<boolean>>; setValue; capitalizeFirstLetter: (item: string) => string; setMapCity: React.Dispatch<React.SetStateAction<undefined>>; setMapState: React.Dispatch<React.SetStateAction<undefined>>; data; formatPhoneNumber: (input: any) => any; setNumber: React.Dispatch<React.SetStateAction<string>>; setSubscribeStatus: React.Dispatch<React.SetStateAction<number>>; setFirstName: React.Dispatch<React.SetStateAction<string>>; setLastName: React.Dispatch<React.SetStateAction<string>>; setbusinessEmail: React.Dispatch<React.SetStateAction<string>>; setCarrierUsername: React.Dispatch<React.SetStateAction<string>>; setselectedbillingDestination: React.Dispatch<React.SetStateAction<string>>; setSelectedOriginDestination: React.Dispatch<React.SetStateAction<string>>; setcompanyName: React.Dispatch<React.SetStateAction<string>>; }) {
  getCarrierparsonalDetails(token, carrierId).then((response) => {
    setIsloading(true);
    if (response?.status == "success") {
      setValue("firstName", capitalizeFirstLetter(response?.data?.first_name));
      setValue("lastName", capitalizeFirstLetter(response?.data?.last_name));
      setValue("business_email", response?.data?.email);
      setValue("billing_address", response?.data?.billing_address);

      setValue("current_address", response?.data?.current_address);
      const parts = response?.data?.current_address?.split(",");
      const city = parts[0].trim();
      const stateAndZip = parts[1].trim();
      const lastSpaceIndex = stateAndZip.lastIndexOf(" ");

      const state = stateAndZip.slice(0, lastSpaceIndex).trim();

      setMapCity(city);
      setMapState(state);
      if (data?.user?.group_type !== "carriers") {
        setValue("current_address", response?.data?.current_address);
      }
      setValue("billing_address", response?.data?.billing_address);

      setValue("company_name", response?.data?.billing_company);
      setValue("phone_number", formatPhoneNumber(response.data?.phone));
      setNumber(formatPhoneNumber(response?.data.phone));
      setSubscribeStatus(response?.data?.is_subscribed);
      setFirstName(response?.data?.first_name);
      setLastName(response?.data?.last_name);
      setbusinessEmail(response?.data?.email);
      setCarrierUsername(response?.data?.username);
      setselectedbillingDestination(response?.data?.billing_address);
      setSelectedOriginDestination(response?.data?.current_address);
      setcompanyName(response?.data?.billing_company);
      setIsloading(false);
    } else {
      setIsloading(false);
    }
  });
}

function blockHandler(event: any) {
  const charCode = event.which;
  if (
    !((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122))
  ) {
    event.preventDefault();
  }
}

function SwitchScope(
  field: string,
  firstname: string,
  lastName: string,
  businessEmail: string,
  number: string,
  companyName: string
) {
  switch (field) {
    case "firstName":
      return firstname;
    case "lastName":
      return lastName;
    case "business_email":
      return businessEmail;
    case "phone_number":
      return number;
    default:
      return companyName;
  }
}

function searchSujjestionScope(
  searchedSuggestions: never[]
): string | undefined {
  return searchedSuggestions.length < 1 ? "d-none" : "";
}

function originScope12(
  selectedOriginDestination: string,
  errors,
  customeAddressError: string
): React.ReactNode {
  return (
    selectedOriginDestination === "" &&
    (errors.current_address?.message?.toString() ?? customeAddressError)
  );
}

function jsxBtwContent(
  { data, checked, spacehandler, sameAddressHandler, register, selectedbillingDestination, errors, customeAddressError, handleAddressChange, setselectedbillingDestination, setSearchbillingSuggestions, setCustomeAddressError, getHideClass, searchedbillingSuggestions, bindbillingSelectedAddress }: {
    data; checked: boolean; spacehandler: (event: any) => void; sameAddressHandler: (e: any) => void; register; selectedbillingDestination: string; errors; customeAddressError: string; handleAddressChange: (
      event: React.ChangeEvent<HTMLInputElement>,
      setAddressValue: (value: string) => void,
      setSuggestions: (suggestions: any[]) => void
    ) => Promise<void>; setselectedbillingDestination: React.Dispatch<React.SetStateAction<string>>; setSearchbillingSuggestions: React.Dispatch<React.SetStateAction<never[]>>; setCustomeAddressError: React.Dispatch<React.SetStateAction<string>>; getHideClass: () => "" | "d-none"; searchedbillingSuggestions: never[]; bindbillingSelectedAddress: (item: SelectAddressType) => void;
  }): React.ReactNode {
  return data?.user?.group_type !== "carriers" ? (
    <div className='col-md-4 mb-3 mt-1'>
      <div className='form-check-inline'>
        <label className='form-check-label'>
          <input
            type='checkbox'
            className='form-check-input'
            checked={checked}
            onKeyDown={spacehandler}
            onChange={sameAddressHandler}
          />
          &nbsp;Same as Current address :
        </label>
      </div>

      <div className='auto_fill'>
        <FormLabel htmlFor='billing_address'>Billing Address:</FormLabel>
        <div className='address-autocomplete-parent'>
          <FormControl
            {...register("billing_address")}
            className={billingAddScope(
              selectedbillingDestination,
              errors,
              customeAddressError
            )}
            id='origin_destination'
            placeholder='Billing address'
            autoComplete='off'
            onKeyDown={spacehandler}
            onInput={(e) => {
              e.preventDefault();
              handleAddressChange(
                e,
                (value) => setselectedbillingDestination(value),
                setSearchbillingSuggestions
              );
            }}
            value={selectedbillingDestination}
            onChange={(e) => {
              setselectedbillingDestination(e.target.value);
              setCustomeAddressError("");
            }}
          />

          <div className={getHideClass()}>
            <ul className='city-listing-css' style={{ zIndex: 99 }}>
              {searchedbillingSuggestions.map((item: any) => (
                <li
                  key={item.name}
                  onClick={() => {
                    bindbillingSelectedAddress({
                      name: item.name,
                      lat: item.lat,
                      lng: item.lng,
                      state_code: item.state_code,
                      post_code: item.post_code,
                    });
                    setselectedbillingDestination(item.name);
                  }}
                >
                  <div className='mb-3'>{item?.name}</div>
                </li>
              ))}
            </ul>
          </div>

          <Form.Control.Feedback type='invalid'>
            {invalidScope(
              selectedbillingDestination,
              errors,
              customeAddressError
            )}
          </Form.Control.Feedback>
        </div>
      </div>
    </div>
  ) : (
    ""
  );
}

function billingAddScope(
  selectedbillingDestination: string,
  errors,
  customeAddressError: string
): string | undefined {
  return (
    ((selectedbillingDestination === "" && errors.billing_address) ||
      customeAddressError) &&
    "is-invalid"
  );
}

function invalidScope(
  selectedbillingDestination: string,
  errors,
  customeAddressError: string
): React.ReactNode {
  return (
    (selectedbillingDestination === "" &&
      errors.billing_address?.message?.toString()) ??
    customeAddressError
  );
}

function jsxContent22(
  userData: undefined,
  buttonDisable: boolean
): React.ReactNode {
  return userData?.EditPersonalDetailstab ? (
    <div className='col-12 but-center'>
      <button
        disabled={buttonDisable}
        type='submit'
        className='btn btn-primary divStylecss-update'
      >
        Save
      </button>
    </div>
  ) : (
    ""
  );
}

function billingScope1(data, FormData: any) {
  return data?.user?.group_type === "carriers" ? " " : FormData.billing_address;
}

function SubmitScopeCondition(
  response: any,
  setButtonDisable: React.Dispatch<React.SetStateAction<boolean>>,
  setIsloading: React.Dispatch<React.SetStateAction<boolean>>,
  setValue
) {
  if (response.status == "success") {
    setButtonDisable(false);
    setIsloading(false);
    toast.success(response?.message, {
      position: toast.POSITION.TOP_CENTER,
    });
    setValue("currentpassword", "");
    setValue("newpassword", "");
    setValue("confirmpassword", "");
  } else {
    setButtonDisable(false);
    setIsloading(false);
    toast.error(response?.message, {
      position: toast.POSITION.TOP_CENTER,
    });
    setValue("currentpassword", "");
    setValue("newpassword", "");
    setValue("confirmpassword", "");
  }
}

function FormControlComponent({
  type,
  id,
  placeHolder,
  register,
  errors,
}: PropTypes) {
  return (
    <FormControl
      type={type}
      {...register(id)}
      id={id}
      autoComplete='off'
      placeholder={placeHolder}
      className={errors[id] && "is-invalid"}
    />
  );
}

function CustomFormControl({
  state,
  id,
  register,
  placeHolder,
  errors,
  onChange,
}: CustomPropType) {
  return (
    <FormControl
      type={state ? "text" : "password"}
      {...register(id)}
      id={id}
      autoComplete='off'
      placeholder={placeHolder}
      onChange={onChange}
      className={errors[id] ? "is-invalid" : ""}
    />
  );
}

interface ImgProps {
  field: string;
  errors: any;
  state: boolean;
  setState: any;
  alt: string;
}

function PasswordVisibilityImage(props: ImgProps) {
  const { field, errors, state, setState, alt } = { ...props };
  return (
    <span
      className={`icon_input`}
      style={{
        position: "absolute",
        top: "6px",
        right: `${errors[field] ? "20px" : "0px"}`,
      }}
    >
      <Image
        className='passwordIcon  show-hide-icon'
        onClick={() => setState(!state)}
        alt={alt}
        width={20}
        height={20}
        src={state ? "/images/pass.png" : "/images/hidepassword.png"}
      />
    </span>
  );
}
