import React, { useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string, SchemaOf } from "yup";
import { FormLabel, FormControl,Button } from "react-bootstrap";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";

import {
  BillingInfoUpdate,
  
} from "../../../services/profile";

import { getStates } from "../../../services/public";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
interface FormData {
  billing_phone: string;
  billing_fax: string;
  billing_city: string;
  country: string;
  billing_state_code: string;
  billing_zip: string;
  billing_email: string;
  billing_contact: string;
  billing_contact_email:string
}
const schema: SchemaOf<FormData> = object().shape({
  billing_phone: string()
  .required("Billing phone is required")
  .matches(/^\d{10}$/, "Phone number must have 10 digits"),
billing_fax: string()
  .required("Billing fax is required")
  .matches(/^\d{10}$/, "Fax number must have 10 digits"),
  billing_city: string()
    .required("Billing city is required")
    .min(2, "Minimum 2 characters required")
    .max(50, "Maximum 50 characters allowed"),
  country: string(),
  billing_state_code: string().required("Billing state is required"),
  billing_zip: string()
    .required(" Billing zip is required")
    .matches(/^\d{5}(?:[-\s]\d{4})?$/, "Please enter a valid billing zip code"),
  billing_email: string()
    .required("Billing email is required")
    .matches(
      /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,
      "Please enter a valid billing email address"
    )
    .max(50, "Maximum 50 characters allowed"),

  billing_contact: string()
    .required("Billing contact is required")
    .max(50, "Maximum 50 characters allowed"),
});
function BillingInfoDetails(prop): JSX.Element {
  const router = useRouter();
  const [formattedPhone, setFormattedPhone] = useState("");
  const [disabled, setDisabled] = useState(true);
  const [formattedfax, setFormattedfax] = useState("");
  const [faxErrorVisible] = useState(false);
  const [states, setStates] = useState([]);
  const [phoneErrorVisible, setPhoneErrorVisible] = useState(false);
  const { data } = useSession();
  const token = data?.user?.image;
  const id = data?.user?.id;
  const userId = router?.query?.id;


  const filteredStates = states?.filter(
    (state) => state?.country_code === "US",
  );
  function prefillData(userDetails) {
    
    const formattedBillingPhone = userDetails?.billing_phone ? userDetails?.billing_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("billing_phone", formattedPhoneNumber !== null ? formattedDisplayNumberAsNumber : null);
    setFormattedPhone(formattedPhoneNumber !== null ? formattedPhoneNumber : "N/A");
    setFormattedPhone(formattedBillingPhone);
    setFormattedfax(userDetails?.billing_fax);
    setValue("billing_fax", userDetails?.billing_fax);
    setValue("billing_city", userDetails?.billing_city);
    setValue("country", userDetails?.country);
    setValue("billing_state_code", userDetails?.billing_state_code);
    setValue("billing_zip", userDetails?.billing_zip);
    setValue("billing_email", userDetails?.billing_email);
    setValue("billing_contact", userDetails?.billing_contact);

  }
  useEffect(() => {
    getStates()
      .then((response) => {
        setStates(response?.data);
      })
      .catch((error) => {
        return error;
      });
  }, []);
  
  useEffect(() => {
    prefillData(prop?.prop?.data?.details?.billing_info)
  }, [prop?.prop?.data?.details?.billing_info]);
  const {
    handleSubmit,
    control,
    setValue,
    reset,
    formState: { errors },
  } = useForm<FormData>({
    resolver: yupResolver(schema),
    defaultValues: {
      billing_phone: "",
      billing_fax: "",
      billing_city: "",
      country: "",
      billing_state_code: "",
      billing_zip: "",
      billing_email: "",
      billing_contact: "",
    },
  });

  const handleCustomerUpdate = async (
    accesstoken: any,
    id1: any,
    payload: any,
  ) => {
    const response = await BillingInfoUpdate(
      accesstoken,
      id1,
      payload,
    );
    if (response?.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      setDisabled(true);
      prop?.setRefresh(true);
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  const onSubmit = async (payload: FormData) => {
    if (phoneErrorVisible || faxErrorVisible) {
      return
    }
    payload.user_id = userId

        await handleCustomerUpdate(token, id, payload);
    
  };

  const handlePhoneChange = (event: { target: { value: string } }) => {
    let inputValue = event.target.value;
    const cleanedInput = inputValue.replace(/\D/g, "");
    const formattedNumber = cleanedInput.slice(0, 10);

    if (formattedNumber.length < 10) {
      setPhoneErrorVisible(true);
    } else {
      setPhoneErrorVisible(false);
    }

    const formattedDisplayNumber = formattedNumber.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3"
    );

    const numberWithHyphens = formattedDisplayNumber.replace(/-/g, '');
    const number = parseInt(numberWithHyphens, 10); 

    setValue("billing_phone", number);
    setFormattedPhone(formattedDisplayNumber);
  };

  const handleFaxChange = (event: { target: { value: any } }) => {
    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",
    );
    setValue("billing_fax", formattedNumberfax);
    setFormattedfax(formattedDisplayNumberfax);
  };
const [collapsed,setCollapsed] = useState(false);
  const renderEditButton = () => {
    if (disabled) {
      return (
        <div className='edit_btn_block' onClick={() => setDisabled(!disabled)}>
          <a className='btn_edit'>
            <span>
              <svg
                xmlns='http://www.w3.org/2000/svg'
                width='14'
                height='15'
                viewBox='0 0 14 15'
                fill='#060707'
              >
                <g clipPath='url(#clip0_1098_1233)'>
                  <path
                    d='M8.20167 5.76167L8.73833 6.29833L3.45333 11.5833H2.91667V11.0467L8.20167 5.76167ZM10.3017 2.25C10.1558 2.25 10.0042 2.30833 9.89333 2.41917L8.82583 3.48667L11.0133 5.67417L12.0808 4.60667C12.3083 4.37917 12.3083 4.01167 12.0808 3.78417L10.7158 2.41917C10.5992 2.3025 10.4533 2.25 10.3017 2.25ZM8.20167 4.11083L1.75 10.5625V12.75H3.9375L10.3892 6.29833L8.20167 4.11083Z'
                    fill='#060707'
                  />
                </g>
                <defs>
                  <clipPath id='clip0_1098_1233'>
                    <rect width='14' height='14' fill='white' transform='translate(0 0.5)' />
                  </clipPath>
                </defs>
              </svg>
            </span>{" "}
            Edit
          </a>
        </div>
      );
    } else {
      return (
        <div style={{ textAlign: "end" }}>
          <button
            onClick={() => {
              setDisabled(!disabled); 
              reset(); 
              prop?.setRefresh(true);
              setFormattedfax('');
            }}
            type='button'
            className='btn btn-primary'
          >
            Cancel
          </button>
        </div>
      );
    }
  };

  return (
    <div className="details_bot">
      <div className="profile_edit_body-detail accordion_cls my-3">
        <div onClick={() => setCollapsed(!collapsed)} className="profile_heading-general link_general ">
          <h3>Billing information Details</h3>
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down-fill" viewBox="0 0 16 16">
            <path d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z" />
          </svg>
        </div>
        {collapsed ? <div>
          <ToastContainer />
          {renderEditButton()}
          <form className="row g-4" onSubmit={handleSubmit(onSubmit)}>
            <div className="col-md-3  ">
              <FormLabel htmlFor="inputbilling_contact">
                Billing Contact:
              </FormLabel>
              <Controller
                name="billing_contact"
                control={control}
                render={({ field }) => (
                  <FormControl
                    disabled={disabled}
                    type="text"
                    className={`form-control ${errors.billing_contact ? "is-invalid" : ""
                      }`}
                    id="inputbilling_contact"
                    {...field}
                  />
                )}
              />
              {errors.billing_contact && (
                <p className="text-danger">{errors.billing_contact.message}</p>
              )}
            </div>

            <div className="col-md-3  ">
              <FormLabel htmlFor="inputbilling_city">Phone:</FormLabel>
              <Controller
                name="billing_phone"
                control={control}
                render={({ field }) => (
                  <FormControl
                    disabled={disabled}
                    type="text"
                    className={`form-control ${errors.billing_phone ? "is-invalid" : ""
                      }`}
                    id="inputbilling_city"
                    {...field}
                    onChange={handlePhoneChange}
                    value={formattedPhone}
                  />
                )}
              />
              {errors.billing_phone && (
                <p className="text-danger">{errors.billing_phone.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <FormLabel htmlFor="inputbilling_fax">Fax:</FormLabel>
              <Controller
                name="billing_fax"
                control={control}
                render={({ field }) => (
                  <FormControl
                    disabled={disabled}
                    type="text"
                    className={`form-control ${errors.billing_fax ? "is-invalid" : ""
                      }`}
                    id="inputbilling_fax"
                    {...field}
                    onChange={handleFaxChange}
                    value={formattedfax}
                  />
                )}
              />
            
              {errors.billing_fax && (
                <p className="text-danger">{errors.billing_fax.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <FormLabel htmlFor="inputZip">Billing Email:</FormLabel>
              <Controller
                name="billing_email"
                control={control}
                render={({ field }) => (
                  <FormControl

                    disabled={disabled}
                    type="text"
                    className={`form-control ${errors.billing_email ? "is-invalid" : ""
                      }`}
                    id="inputZip"
                    {...field}
                  />
                )}
              />
              {errors.billing_email && (
                <p className="text-danger">{errors.billing_email.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <FormLabel htmlFor="inputbilling_city">City:</FormLabel>
              <Controller
                name="billing_city"
                control={control}
                render={({ field }) => (
                  <FormControl
                    disabled={disabled}

                    type="text"
                    className={`form-control ${errors.billing_city ? "is-invalid" : ""
                      }`}
                    id="inputbilling_city"
                    {...field}
                  />
                )}
              />
              {errors.billing_city && (
                <p className="text-danger">{errors.billing_city.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <div className="select_group">
                <FormLabel htmlFor="inputbilling_state_code">Country:</FormLabel>
                <Controller
                  name="country"
                  control={control}
                  defaultValue="US"
                  render={({ field }) => (
                    <FormControl
                      as="select"
                      id="inputbilling_state_code"
                      disabled
                      className={`form-select ${errors.country ? "is-invalid" : ""
                        } `}
                      {...field}
                    >
                      <option selected value="US">
                        US
                      </option>
                    </FormControl>
                  )}
                />
              </div>
              {errors.country && (
                <p className="text-danger">{errors.country.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <div className="select_group">
                <FormLabel htmlFor="inputbilling_state_code">State:</FormLabel>
                <Controller
                  name="billing_state_code"
                  control={control}
                  render={({ field }) => (
                    <FormControl
                      disabled={disabled}

                      as="select"
                      id="inputbilling_state_code"
                      className={`form-select ${errors.billing_state_code ? "is-invalid" : ""
                        }`}
                      {...field}
                    >
                      <option value="">---Select State---</option>{" "}
                      {filteredStates?.map((item, i) => {
                        return (
                          <>
                            <option value={item?.state_code}>
                              {item?.state_name}{" "}
                            </option>
                          </>
                        );
                      })}
                    </FormControl>
                  )}
                />
              </div>
              {errors.billing_state_code && (
                <p className="text-danger">{errors.billing_state_code.message}</p>
              )}
            </div>
            <div className="col-md-3  ">
              <FormLabel htmlFor="inputbilling_zip">Zip:</FormLabel>
              <Controller
                name="billing_zip"
                control={control}
                render={({ field }) => (
                  <FormControl
                    disabled={disabled}

                    type="text"
                    className={`form-control ${errors.billing_zip ? "is-invalid" : ""
                      }`}
                    id="inputbilling_zip"
                    {...field}
                  />
                )}
              />
              {errors.billing_zip && (
                <p className="text-danger">{errors.billing_zip.message}</p>
              )}
            </div>
            <div className='col-12 primary-save'>
              <Button
                hidden={disabled}
                type='submit'
                className='btn btn-primary'
              >
                Update
              </Button>
            </div>
          </form>
        </div>:""}
      
      </div>
    </div>
  );
}

export default BillingInfoDetails;
