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 { WebsiteRules } from "@/utils/regex/regex";
import {
  BusinessAddressUpdate,
  BusinessAddressUpdateCarrier,
} 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 {
  business_phone: string;
  business_fax: string;
  business_city: string;
  country: string;
  business_state_code: string;
  business_zip: string;
  business_contact_email: string;
  business_address: string;
  scac: string;
}

function validateWebsite(value) {
  const regexPattern = WebsiteRules;
  return regexPattern.test(value);
}

function BusinessAddress(): JSX.Element {
  const [states, setStates] = useState([]);
  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 { Permission: userData } = useAuthProvider();

  const filteredStates = states?.filter(
    (state) => state?.country_code === "US"
  );

  const isValidPhoneNumber = (value: unknown) => {
    if (!value) return true;
    const stringValue = String(value);
    return stringValue.length === 12;
  };
  
  const schema: SchemaOf<FormData> = object().shape({
    business_phone: string()
    .required("Business phone number is required")
    .test("is-valid-phone", "Business phone number must be 10 digits", isValidPhoneNumber),
    business_fax: string()
    .required("Business fax number is required")
    .test("is-valid-phone", "Business fax number must be 10 digits", isValidPhoneNumber),
    business_city: string().required("Business city is required"),
    country: string().required("Country is required"),
    business_state_code: string().required("Business state is required"),
    business_zip: string()
      .required("Business zip is required")
      .matches(/^\d{5}$/, "Invalid business zip code format")
      .min(5, "Business zip code must be at least 5 digits long")
      .max(10, "Business zip code cannot exceed 10 digits"),

    business_address: string()
      .required("Business address is required")
      .max(100, "Business address cannot exceed 100 characters"),
  });
  function prefillData(userDetails) {
    setValue("business_phone", userDetails.business_phone);
    setValue("business_fax", userDetails.business_fax);
    setValue("business_city", userDetails.business_city);
    setValue("country", "US");
    {
      carrierUser ? setValue("business_state_code", userDetails.state_name) : setValue("business_state_code", userDetails.business_state_code);
 }
    setValue("business_zip", userDetails.business_zip);
    setValue("business_contact_email", userDetails.business_contact);
    setValue("business_address", userDetails.business_address);
  }

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await getStates();
        setStates(response?.data);
      } catch (error) {
        return error;
      }
    };

    fetchData();
  }, []);

  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);
    }
  }, [token]);

  const {
    handleSubmit,
    control,
    setValue,
    formState: { errors },
  } = useForm<FormData>({
    resolver: yupResolver(schema),
  });
  const handleCarrierUpdate = async (tokenpass, idpass, payload) => {
    const response = await BusinessAddressUpdateCarrier(
      tokenpass,
      idpass,
      payload
    );
    if (response?.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };

  const handleCustomerUpdate = async (accesstoken, id3, payload) => {
    const response = await BusinessAddressUpdate(accesstoken, id3, payload);
    if (response?.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      fetchUserDetails(data?.user?.image, data?.user?.id);
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  const onSubmit = async (payload) => {    
    try {
      const modifiedPayload = {
        business_phone: payload.business_phone,
        business_fax: payload.business_fax,
        business_city: payload.business_city,
        country: payload.country,
        ...(carrierUser
          ? { state_name: payload.business_state_code }
          : { business_state_code: payload.business_state_code }
        ),
        business_zip: payload.business_zip,
        business_address: payload.business_address,
      };
      if (customerUser) {
        await handleCustomerUpdate(
          data?.user?.image,
          data?.user?.id,
          modifiedPayload
        );
      }
      if (carrierUser) {
        await handleCarrierUpdate(
          data?.user?.image,
          carrierId,
          modifiedPayload
        );
      }
    } catch (error) {
      return error;
    }
  };

  const formatPhoneNumber = (value: string) => {
    const cleaned = value.replace(/\D/g, "").slice(0, 10);
    return cleaned.length === 10 ? cleaned.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3") : cleaned;
  };

  const handlePhoneChange = (event: { target: { value: any } }) => {
    setValue("business_phone", formatPhoneNumber(event.target.value));
  };

  const handleFaxChange = (event: { target: { value: any } }) => {
    setValue("business_fax", formatPhoneNumber(event.target.value));
  };

  return (
    <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-6'>
              <FormLabel htmlFor='business_phone'>Phone:</FormLabel>
              <Controller
                name='business_phone'
                control={control}
                render={({ field }) => (
                  <div>
                    <FormControl
                      type='text'
                      className={`form-control ${
                        errors.business_phone ? "is-invalid" : ""
                      }`}
                      id='business_phone'
                      {...field}
                      onChange={handlePhoneChange}
                    />
                    {errors.business_phone && (
                      <p className='text-danger'>
                        {errors.business_phone.message}
                      </p>
                    )}
                  </div>
                )}
              />
            </div>
            <div className='col-md-6  '>
              <FormLabel htmlFor='business_fax'>Fax:</FormLabel>
              <Controller
                name='business_fax'
                control={control}
                render={({ field }) => (
                  <FormControl
                    type='text'
                    className={`form-control ${
                      errors.business_fax ? "is-invalid" : ""
                    }`}
                    id='business_fax'
                    {...field}
                    onChange={handleFaxChange}
                  />
                )}
              />
              {errors.business_fax && (
                <p className='text-danger'>{errors.business_fax.message}</p>
              )}
            </div>
            <div className='col-md-3  '>
              <FormLabel htmlFor='business_city'>City:</FormLabel>
              <Controller
                name='business_city'
                control={control}
                render={({ field }) => (
                  <FormControl
                    type='text'
                    className={`form-control ${
                      errors.business_city ? "is-invalid" : ""
                    }`}
                    id='business_city'
                    {...field}
                  />
                )}
              />
              {errors.business_city && (
                <p className='text-danger'>{errors.business_city.message}</p>
              )}
            </div>
            <div className='col-md-3  '>
              <div className='select_group'>
                <FormLabel htmlFor='inputState'>Country:</FormLabel>
                <Controller
                  name='country'
                  control={control}
                  defaultValue='US'
                  render={({ field }) => (
                    <FormControl
                      as='select'
                      id='inputState'
                      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>

            {carrierUser ? <div className='col-md-3'>
              <div className='select_group'>
                <FormLabel htmlFor='inputState'>State:</FormLabel>
                <Controller
                  name='business_state_code'
                  control={control}
                  render={({ field }) => (
                    <FormControl
                      type='text'
                      className={`form-control ${errors.business_state_code ? "is-invalid" : ""
                        }`}
                      id='business_state_code'
                      {...field}
                    />
                  )}
                />
              </div>
              {errors.business_state_code && (
                <p className='text-danger'>
                  {errors.business_state_code.message}
                </p>
              )}
            </div> : <div className='col-md-3'>
              <div className='select_group'>
                <FormLabel htmlFor='inputState'>State:</FormLabel>
                <Controller
                  name='business_state_code'
                  control={control}
                  render={({ field }) => (
                    <FormControl
                      as='select'
                      id='inputState'
                      className={`form-select ${errors.business_state_code ? "is-invalid" : ""
                        }`}
                      {...field}
                    >
                      <option value=''>---Select State---</option>
                      {filteredStates?.map((item, i) => (
                        <option key={i} value={item?.state_code}>
                          {item?.state_name}
                        </option>
                      ))}
                    </FormControl>
                  )}
                />
              </div>
              {errors.business_state_code && (
                <p className='text-danger'>
                  {errors.business_state_code.message}
                </p>
              )}
            </div>}
      

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

            <div className='col-md-12  '>
              <FormLabel htmlFor='address_field'>Address:</FormLabel>
              <Controller
                name='business_address'
                control={control}
                render={({ field }) => (
                  <FormControl
                    as='textarea'
                    className={`form-control ${
                      errors.business_address ? "is-invalid" : ""
                    }`}
                    id='address_field'
                    rows={3}
                    {...field}
                  />
                )}
              />
              {errors.business_address && (
                <p className='text-danger'>{errors.business_address.message}</p>
              )}
            </div>
            
            {userData?.EditBusinessAddresstab ? (
              <div className='col-12 but-center'>
                <Button type='submit' className='btn btn-primary divStylecss-update'>
                  Save
                </Button>
              </div>
            ) : (
              ""
            )}
          </form>
        </div>
      </div>
    </div>
  );
}

export default BusinessAddress;
