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 } from "react-bootstrap";
import { useSession } from "next-auth/react";
import {
  CustomerBillingAddressUpdate,
  CarrierBillingAddressUpdate,
} from "../../../services/profile";
import {
  getSingleCustomers,
  getSingleCarrier,
} from "../../../services/customers";
import { getStates } from "../../../services/public";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import useAuthProvider from "@/useAuthProvider";
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_email: string;
}
const schema: SchemaOf<FormData> = object().shape({
  billing_phone: string().nullable(),
  billing_fax: string().nullable(),
  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"
        ),
  billing_contact_email: string()
    .required("Billing contact is required")
    .max(50, "Maximum 50 characters allowed"),
});
function BillingAddress(): JSX.Element {
  const { Permission: userData } = useAuthProvider();

  const [formattedPhone, setFormattedPhone] = useState("");
  const [formattedfax, setFormattedfax] = useState("");
  const [faxErrorVisible, setFaxErrorVisible] = 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 carrierId = data?.user?.carrier_id;
  const customerUser = data?.user?.group_type === "customers";
  const carrierUser = data?.user?.group_type === "carriers";
  const filteredStates = states?.filter(
    (state) => state?.country_code === "US",
  );
  function prefillData(userDetails: any) {
    
    const formattedBillingPhone = userDetails?.billing_phone ? userDetails?.billing_phone.replace(/\D/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3') : '';
    const formattedPhoneNumber = formattedBillingPhone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    setFormattedfax(userDetails?.billing_fax ? userDetails?.billing_fax:"");
    setFormattedPhone(formattedPhoneNumber ? formattedPhoneNumber:"");
    setValue("billing_phone", formattedPhoneNumber ? formattedPhoneNumber:"");
    setValue("billing_fax", userDetails?.billing_fax ? userDetails?.billing_fax:"");
    setValue("billing_city", userDetails?.billing_city ? userDetails?.billing_city:"");
    setValue("country", userDetails?.country ? userDetails?.country:"");
    setValue("billing_state_code", userDetails?.billing_state_code ? userDetails?.billing_state_code:"");
    setValue("billing_zip", userDetails?.billing_zip ? userDetails?.billing_zip:"");
    setValue("billing_email", userDetails?.billing_email ? userDetails?.billing_email:"");
    setValue("billing_contact_email", userDetails?.billing_contact ? userDetails?.billing_contact:"");
  }
  
  useEffect(() => {
    getStates()
      .then((response) => {
        setStates(response?.data);
      })
      .catch((error) => {
        return error;
      });
  }, []);
  const fetchCarrierDetails = (token1: any, id1: any) => {
    return getSingleCarrier(token1, id1)
      .then((response) => {
        const userDetails = response.data;
        prefillData(userDetails);
      })
      .catch((error) => {
        return error;
      });
  };

  const fetchUserDetails = (image: any, id2: any) => {
    return getSingleCustomers(image, id2)
      .then((response) => {
        const userDetails = response.data;
        prefillData(userDetails);
      })
      .catch((error) => {
        return error;
      });
  };
  useEffect(() => {
    {
      customerUser && fetchUserDetails(token, id);
    }
    {
      carrierUser && fetchCarrierDetails(token, carrierId);
    }
  }, []);
  const {
    handleSubmit,
    control,
    setValue,
    formState: { errors },
  } = useForm<FormData>({
    resolver: yupResolver(schema),
  });
  const handleCarrierUpdate = async (
    tokenpass: any,
    idpass: any,
    payload: any,
  ) => {
    const response = await CarrierBillingAddressUpdate(
      tokenpass,
      idpass,
      payload,
    );
    if (response?.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      
      fetchCarrierDetails(token, carrierId);
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  const handleCustomerUpdate = async (
    accesstoken: any,
    id1: any,
    payload: any,
  ) => {
    const response = await CustomerBillingAddressUpdate(
      accesstoken,
      id1,
      payload,
    );
    if (response?.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      fetchUserDetails(token, id);
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  const onSubmit = async (payload: FormData) => {
    try {
      if (customerUser) {
        await handleCustomerUpdate(token, id, payload);
      }
      if (carrierUser) {
        await handleCarrierUpdate(token, carrierId, payload);
      }
    } catch (error) {
      return error;
    }
  };

  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 < 10) {
      setPhoneErrorVisible(true);
    } else {
      setPhoneErrorVisible(false);
    }
    const formattedDisplayNumber = formattedNumber?.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3",
    );
    setValue("billing_phone", formattedDisplayNumber);
    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);
    if (formattedNumberfax?.length < 10) {
      setFaxErrorVisible(true);
    } else {
      setFaxErrorVisible(false);
    }
    const formattedDisplayNumberfax = formattedNumberfax?.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3",
    );
    setValue("billing_fax", formattedDisplayNumberfax);
    setFormattedfax(formattedDisplayNumberfax);
  };

  return (
    <div>
      <ToastContainer />
      <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-6  ">
          <FormLabel htmlFor="inputbilling_email">Billing Email:</FormLabel>
          <Controller
            name="billing_email"
            control={control}
            render={({ field }) => (
              <FormControl
                type="text"
                className={`form-control ${
                  errors.billing_email ? "is-invalid" : ""
                }`}
                id="inputbilling_email"
                {...field}
              />
            )}
          />
          {errors.billing_email && (
            <p className="text-danger">{errors.billing_email.message}</p>
          )}
        </div>
        <div className="col-md-6  ">
          <FormLabel htmlFor="inputZip">Billing Contact:</FormLabel>
          <Controller
            name="billing_contact_email"
            control={control}
            render={({ field }) => (
              <FormControl
                type="text"  
                className={`form-control ${
                  errors.billing_contact_email ? "is-invalid" : ""
                }`}
                id="inputZip"
                {...field}
              />
            )}
          />
          {errors.billing_contact_email && (
            <p className="text-danger">
              {errors.billing_contact_email.message}
            </p>
          )}
        </div>

        <div className="col-md-6  ">
          <FormLabel htmlFor="inputbilling_city">Phone:</FormLabel>
          <Controller
            name="billing_phone"
            control={control}
            render={({ field }) => (
              <FormControl
                type="text"
                className={`form-control ${
                  errors.billing_phone ? "is-invalid" : ""
                }`}
                id="inputbilling_city"
                {...field}
                onChange={handlePhoneChange}
                value={formattedPhone}
              />
            )}
          />
          {phoneErrorVisible && (
            <p className="text-danger">
              Phone number must have at least 10 digits
            </p>
          )}
          {errors.billing_phone && (
            <p className="text-danger">{errors.billing_phone.message}</p>
          )}
        </div>
        <div className="col-md-6  ">
          <FormLabel htmlFor="inputbilling_fax">Fax:</FormLabel>
          <Controller
            name="billing_fax"
            control={control}
            render={({ field }) => (
              <FormControl
                type="text"
                className={`form-control ${
                  errors.billing_fax ? "is-invalid" : ""
                }`}
                id="inputbilling_fax"
                {...field}
                onChange={handleFaxChange}
                value={formattedfax}
              />
            )}
          />
          {faxErrorVisible && (
            <p className="text-danger">
              Billing fax must have at least 10 digits
            </p>
          )}
          {errors.billing_fax && (
            <p className="text-danger">{errors.billing_fax.message}</p>
          )}
        </div>
        <div className="col-md-3  ">
          <FormLabel htmlFor="inputbilling_city">City:</FormLabel>
          <Controller
            name="billing_city"
            control={control}
            render={({ field }) => (
              <FormControl
                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
                  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
                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 justify-content-center but-center">
          {userData?.ProfileBillingAddressUpdate ? <button type="submit" className="btn btn-primary  divStylecss-update">
            Save
          </button>:""}
      
        </div>
      </form>
    </div>
  );
}

export default BillingAddress;
