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 {
    
    UserAddressUpdateCarrier,
} from "../../../services/profile";
import {
    getSingleCustomers,
    getSingleCarrier,
} from "../../../services/customers";
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 BusinessAddressUser(prop): JSX.Element {
    const [disabled, setDisabled] = useState(true);
    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 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() {
        setValue("business_phone", prop?.prop?.data?.details?.business_address?.business_phone);
        setValue("business_fax", prop?.prop?.data?.details?.business_address?.business_fax);
        setValue("business_city", prop?.prop?.data?.details?.business_address?.business_city);
        setValue("country", "US");
        setValue("business_state_code", prop?.prop?.data?.details?.business_address?.state_name);
        setValue("business_zip", prop?.prop?.data?.details?.business_address?.business_zip);
        setValue("business_contact_email", prop?.prop?.data?.details?.business_address?.business_contact);
        setValue("business_address", prop?.prop?.data?.details?.business_address?.business_address);
    }

    useEffect(() => {
        prefillData()
    }, [prop])

    const fetchCarrierDetails = (token1: any, id1: any) => {
        return getSingleCarrier(token1, id1)
            .then((response) => {
                const userDetails: any = response?.data;
                prefillData(userDetails);
            })
            .catch((error) => {
                return error;
            });
    };

    const fetchUserDetails = (image: any, id2: any) => {
        return getSingleCustomers(image, id2)
            .then((response) => {
                const userDetails: any = response.data;
                prefillData(userDetails);
            })
            .catch((error) => {
                return error;
            });
    };

    useEffect(() => {
        {
            customerUser && fetchUserDetails(token, id);
        }
        {
            carrierUser && fetchCarrierDetails(token, carrierId);
        }
    }, [token, prop]);

    const {
        handleSubmit,
        control,
        setValue,
        formState: { errors },
        reset
    } = useForm<FormData>({
        resolver: yupResolver(schema),
    });

    const handleCarrierUpdate = async (tokenpass: string | null | undefined, payload: { business_phone: any; business_fax: any; business_city: any; country: any; state_name: any; business_zip: any; business_address: any; user_id: any; }) => {
        const response = await UserAddressUpdateCarrier(
            tokenpass,
            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 onSubmit = async (payload: any) => {
        try {
            const modifiedPayload = {
                business_phone: payload.business_phone,
                business_fax: payload.business_fax,
                business_city: payload.business_city,
                country: payload.country,
                state_name: payload.business_state_code ,
                business_zip: payload.business_zip,
                business_address: payload.business_address,
                user_id: prop?.userid,
            };
            
            await handleCarrierUpdate(
                data?.user?.image,
                modifiedPayload
            );
            prop.setRefresh(true);
            setDisabled(true);

        } 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));
    };

    const [collapsed, setCollapsed] = useState(false)
    const showEditBusinessAddressTab = userData?.EditBusinessAddresstab;

    const handleResetValue = ()=>{
        setDisabled(!disabled);
        reset({
            business_phone: '',
            business_fax: '',
            business_city: '',
            country: '',
            business_state_code: '',
            business_zip: '',
            business_contact_email: '',
            business_address: '',
        });
        prop.setRefresh(true);
    }

    const renderEditOrCancelButton = disabled ? (
        <div
            className='edit_btn_block'
            onClick={() => handleResetValue()}
        >
            <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>
    ) : (
        <div style={{ textAlign: "end" }}>
            <button
                onClick={() => handleResetValue()}
                type='button'
                className='btn btn-primary'
            >
                Cancel
            </button>
        </div>
    );
    return (
        <div className="details_bot">
            <div className='profile_edit_body-detail accordion_cls my-3'>
                <ToastContainer />
                <div onClick={() => setCollapsed(!collapsed)} className='profile_heading-general link_general'>
                    <h3>Business Address</h3>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="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
                    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>
                        {renderEditOrCancelButton}

                        <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}
                                                disabled={disabled}

                                            />
                                            {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
                                            disabled={disabled}
                                            autoComplete="off"
                                            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
                                            disabled={disabled}

                                            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
                                                disabled={disabled}

                                                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>

                            <div className='col-md-3'>
                                <div className='select_group'>
                                    <FormLabel htmlFor='inputState'>State:</FormLabel>
                                    <Controller
                                        name='business_state_code'
                                        control={control}
                                        render={({ field }) => (
                                            <FormControl
                                                disabled={disabled}

                                                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  '>
                                <FormLabel htmlFor='business_zip'>Zip:</FormLabel>
                                <Controller
                                    name='business_zip'

                                    control={control}
                                    render={({ field }) => (
                                        <FormControl
                                            disabled={disabled}

                                            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
                                            disabled={disabled}

                                            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>

                            {showEditBusinessAddressTab && (
                                <div style={{ textAlign: "center" }} className='col-12'>
                                    <Button hidden={disabled} type='submit' className='btn btn-primary'>
                                        Save
                                    </Button>
                                </div>
                            )}
                        </form>
                    </div>
                </div> : ""}
                </div>
    </div>
    );
}

export default BusinessAddressUser;
