import { useForm, useFieldArray } from "react-hook-form";
import { AddAdditionalContact } from "@/services/public";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { ToastContainer, toast } from "react-toastify";
import { FormLabel, Button, FormGroup } from "react-bootstrap";
import { useSession } from "next-auth/react";
import { CustomerAdditionalContacts } from "@/services/profile";
import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/router";
export default function CustomerRegData(props:any) {  

  const { data } = useSession();
  const token = data?.user?.image;
  const Router = useRouter();
  const userType = data?.user?.group_type;

  const buttonRef = useRef<HTMLButtonElement>(null);
  function transformData(inputData) {
    const transformedData = {
      id: [],
      name: [],
      position: [],
      phone: [],
      email: [],
    };
    transformedData.id.push(inputData.id);
    transformedData.name.push(inputData.name);
    transformedData.position.push(inputData.position);
    transformedData.phone.push(inputData.phone);
    transformedData.email.push(inputData.email);

    inputData.primarycontacts.forEach((contact) => {
      transformedData.id.push(contact.id);
      transformedData.name.push(contact.name);
      transformedData.position.push(contact.position);
      transformedData.phone.push(contact.phone);
      transformedData.email.push(contact.email);
    });

    return transformedData;
  }

  useEffect(() => {
    buttonReff(props, buttonRef);
  }, [props?.submit]);

  const registerSubmit = async (datas: any) => {
    const transformedData = transformData(datas);
    let res = await AddAdditionalContact(
      transformedData,
      token,
      Router?.query?.id,
    );
    submitFormScope(res, props, fetchData, reset);
  };
  const schema = yup.object().shape({
    is_recived_email: yup.boolean(),
    name: yup
      .string()
      .required("Name is required")
      .max(20, "Maximum 20 characters allowed"),
    email: yup
      .string()
      .email("Please enter a valid email address")
      .nullable()
      .max(40, "Maximum 40 characters allowed"),
    primarycontacts: yup.array().of(
      yup.object().shape({
        name: yup
          .string()
          .required("Name is required")
          .max(20, "Maximum 20 characters allowed"),
        email: yup
          .string()
          .email("Please enter a valid email address")
          .nullable()
          .max(40, "Maximum 40 characters allowed"),
      }),
    ),
  });
  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
    watch,
  } = useForm({
    resolver: yupResolver(schema),
  });
  const { fields, append } = useFieldArray({
    control,
    name: "primarycontacts",
  });

  const [visibleContacts, setVisibleContacts] = useState(false);

  const handleChange = () => {
    props?.disable(false);
  };
  const fetchData = async () => {
    let res = await CustomerAdditionalContacts(token, Router?.query?.id);
    fetchDataScope(res, reset);
  };
  useEffect(() => {
    fetchData();
  }, []);

  const handlePhoneChange = (event, i, o) => {
    handleChange(event);
    let inputValue = event.target.value;
    const cleanedInput = inputValue.replace(/\D/g, "");
    const formattedNumber = cleanedInput.slice(0, 10);
    const formattedDisplayNumber = formattedNumber.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3",
    );
    phoneValueScope(setValue, i, o, formattedDisplayNumber);
  };

  const handleFaxChange = (event, i, o) => {
    handleChange(event);
    let inputValuefax = event.target.value;
    const cleanedInputfax = inputValuefax?.replace(/\D/g, "");
    const formattedNumberfax = cleanedInputfax?.slice(0, 10);
    const formattedDisplayNumberfax = formattedNumberfax?.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3",
    );
    faxScope(setValue, i, o, formattedDisplayNumberfax);
  };
  const handleShowAll = () => {
    showAllScope(visibleContacts, fetchData, setVisibleContacts);
  };

  const handleAddContact = () => {
    append({});
    setVisibleContacts(true);
  };
  const buttonText = textButtonScope(visibleContacts, fields);

  const newLocal = fields.map(({ id }, index) => (
    <>
      <div key={id}>
        <div className=" ">
          <div
            className="d-flex justify-content-end "
            style={{
              marginTop: " -1.5rem !important",
              padding: "10px",
            }}
          >
            <p></p>
            {/* <i className="bi bi-x cut-icon" onClick={() => remove(index)}></i> */}
          </div>
          <div style={{ display: "none" }} className="classCol">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="id"
            >
              id:
            </FormLabel>
            <input
              {...register("id")}
              value={null}
              placeholder="id"
              type="text"
              className="form-control" />
          </div>
          <div className="classCol">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="name"
            >
              Name:
            </FormLabel>
            <input
              {...register(`primarycontacts[${index}].name`, {
                onChange: (e) => handleChange(e),
              })}
              placeholder="Enter Name"
              
              type="text"
              className="form-control" />
          </div>
          {errors.primarycontacts &&
            errors.primarycontacts[index] &&
            errors.primarycontacts[index].name && (
              <p
                className="text-danger mb-1 z-1"
                style={{ fontSize: "11px", textAlign: "end" }}
              >
                {errors.primarycontacts[index].name.message}
              </p>
            )}
          <div className="classCol">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="name"
            >
              Position:
            </FormLabel>
            <input
              {...register(`primarycontacts[${index}].position`, {
                onChange: (e) => handleChange(e),
              })}
              placeholder="Enter Position"
            
              type="text"
              className="form-control" />
            {errors.primarycontacts &&
              errors.primarycontacts[index] &&
              errors.primarycontacts[index].position && (
                <p className="text-danger">
                  {errors.primarycontacts[index].position.message}
                </p>
              )}
          </div>
          <div style={{ display: "none" }} className="col-md-6">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="name"
            >
              Primary:
            </FormLabel>
            <input
              {...register(`primarycontacts[${index}].primary`)}
              placeholder="Enter primary"
              type="text"
              defaultValue="0"
              value="0"
              className="form-control" />
          </div>
          <div className="classCol">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="name"
            >
              Phone:
            </FormLabel>
            <input
              {...register(`primarycontacts[${index}].phone`, {
                onChange: (e) => handleChange(e),
              })}
              placeholder="Enter Phone"
              type="text"
              onChange={(e) => handleFaxChange(
                e,
                2,
                `primarycontacts[${index}].phone`
              )}
              value={watch(`primarycontacts[${index}].phone`) || ""}
              className="form-control" />
          </div>
          <div className="classCol">
            <FormLabel
              className="info-user lable-info form-label"
              htmlFor="name"
            >
              Email:
            </FormLabel>
            <input
              {...register(`primarycontacts[${index}].email`, {
                onChange: (e) => handleChange(e),
              })}
              placeholder="Enter Email"
            
              type="text"
              className="form-control" />
            {errors.primarycontacts &&
              errors.primarycontacts[index] &&
              errors.primarycontacts[index].email && (
                <p
                  className="text-danger mb-1 z-1"
                  style={{ fontSize: "11px", textAlign: "end" }}
                >
                  {errors.primarycontacts[index].email.message}
                </p>
              )}
          </div>
        </div>
      </div>
    </>
  ));
  
  return (
    <>
      <ToastContainer />
      <div className="App">
        <form onSubmit={handleSubmit(registerSubmit)}>
          {data != null && userType === "customers" ? (
            <div className="">
              <div className="-1.5rem Form-class">
                <h6 className="carriers-h6">
                  <b>Customers Additional Contacts</b>
                </h6>
              </div>

              <div style={{ display: "none" }} className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="id"
                >
                  id:
                </FormLabel>
                <input
                  {...register("id")}
                  value={null}
                  placeholder="id"
                  type="text"
                  className="form-control"
                />
              </div>
              <div className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="name"
                >
                  Name:
                </FormLabel>
                <input
                  {...register("name", {
                    onChange: (e) => handleChange(e),
                  })}
                  placeholder="Enter Name"
                  type="text"
                  className="form-control"
                />
              
              </div>
              {errors && errors.name && (
                <p
                  className="text-danger mb-1 z-1"
                  style={{ fontSize: "11px", textAlign: "end" }}
                >
                  {errors.name.message}
                </p>
              )}
              <div className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="name"
                >
                  Position:
                </FormLabel>
                <input
                  {...register("position", {
                    onChange: (e) => handleChange(e),
                  })}
                  placeholder="Enter Position"
                  type="text"
                  className="form-control"
                />
                {errors && errors.position && (
                  <p className="text-danger">{errors.position.message}</p>
                )}
              </div>
              <div style={{ display: "none" }} className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="name"
                >
                  primary:
                </FormLabel>
                <input
                  {...register("primary")}
                  placeholder="Enter Primary"
                  type="text"
                  value="1"
                  className="form-control"
                />
              </div>
              <div className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="name"
                >
                  Phone:
                </FormLabel>
                <input
                  {...register("phone", {
                    onChange: (e) => handleChange(e),
                  })}
                  placeholder="Enter Phone"
                  type="text"
                  className="form-control"
                  onChange={(e) => handlePhoneChange(e, 1, "")}
                  value={watch("phone")}
                />
              </div>
              <div className="classCol">
                <FormLabel
                  className="info-user lable-info form-label"
                  htmlFor="name"
                >
                  Email:
                </FormLabel>
                <input
                  {...register("email", {
                    onChange: (e) => handleChange(e),
                  })}
                  placeholder="Enter Email"
                  type="text"
                  className="form-control"
                />

                {errors && errors.email && (
                  <p
                    className="text-danger mb-1 z-1"
                    style={{ fontSize: "11px", textAlign: "end" }}
                  >
                    {errors.email.message}
                  </p>
                )}
              </div>
            </div>
          ) : (
            ""
          )}

          <div>
            {visibleContacts
              ?
              newLocal
              : ""}
          </div>

          {fields?.length !== 0 ? (
            <FormGroup
              className="now_con"
              controlId="exampleForm.ControlInput1"
            >
              <Button
                style={{ textDecoration: "none", fontSize: "inherit" }}
                variant="link"
                onClick={handleShowAll}
              >
                {buttonText}
              </Button>
            </FormGroup>
          ) : (
            ""
          )}
          <Button
            ref={buttonRef}
            style={{ display: "none" }}
            type="submit"
            className="btn btn-primary"
          >
            Save
          </Button>
          {userType === "customers" ? (
            <div
              className="col-12 flex gap-2"
              style={{ gap: 10, textAlign: "center" }}
            >
              <br />
              <span onClick={handleAddContact} className="span-add icon-css">
                <i className="bi bi-plus-circle-fill"></i>
              </span>
            </div>
          ) : (
            ""
          )}
        </form>
      </div>
    </>
  );
}
function textButtonScope(visibleContacts: boolean, fields) {
  return !visibleContacts
    ? `Show All Contacts (${fields?.length})`
    : "Hide All Contacts";
}

function showAllScope(visibleContacts: boolean, fetchData: () => Promise<void>, setVisibleContacts) {
  if (visibleContacts) {
    fetchData();
  }
  setVisibleContacts(!visibleContacts);
}

function faxScope(setValue, i: any, o: any, formattedDisplayNumberfax: any) {
  setValue(i === 1 ? "fax" : o, formattedDisplayNumberfax);
}

function phoneValueScope(setValue, i: any, o: any, formattedDisplayNumber: any) {
  setValue(i === 1 ? "phone" : o, formattedDisplayNumber);
}

function fetchDataScope(res: any, reset) {
  if (res?.data?.length > 0) {
    const primaryContact = res.data[0];
    reset({
      id: primaryContact.id,
      name: primaryContact.name,
      position: primaryContact.position,
      phone: primaryContact.phone,
      email: primaryContact.email,
      primarycontacts: res.data.slice(1).map((contact) => ({
        id: contact.id,
        name: contact.name,
        position: contact.position,
        phone: contact.phone,
        email: contact.email,
      })),
    });
  }
}

function submitFormScope(res: any, props: any, fetchData: () => Promise<void>, reset) {
  if (res?.status === "success") {
    toast.success(
      res.message === "Contact has been saved."
        ? "Customer contacts has been saved"
        : "",
      {
        position: toast.POSITION.TOP_CENTER,
      }
    );
    props?.disable(true);
    fetchData();
    reset();
  }
}

function buttonReff(props: any, buttonRef) {
  if (props.submit && buttonRef.current) {
    props.setSubmit(false);
    buttonRef.current.click();
  }
}

