import React, { useEffect, useState } from "react";
import "./Manage_Address.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faPencil,
  faPencilSquare,
  faPenToSquare,
  faTrash,
} from "@fortawesome/free-solid-svg-icons";
import { Form } from "react-bootstrap";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { useForm, Controller } from "react-hook-form";
import Green_round_btn from "../../../common-components/common_btn/green_round_btn/Green_round_btn";
import Green_btn from "../../../common-components/common_btn/green_btn/Green_btn";
import Select from "react-select";
import { useDispatch, useSelector } from "react-redux";
import {
  AllCity,
  AllPincode,
  AllState,
  getAllCountries,
} from "../../../../features/master/masterSlice";
import {
  createOrderAddress,
  EditOrderAddress,
  getAllOrderAddress,
  getSingleOrderAddress,
} from "../../../../features/order/orderSlice";
import { deleteUserAddress } from "../../../../features/user/userSlice";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";

const Manage_Address = () => {
  const options = [
    { value: "chocolate", label: "Chocolate" },
    { value: "strawberry", label: "Strawberry" },
    { value: "vanilla", label: "Vanilla" },
  ];

  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const dispatch = useDispatch();
  const allAddress = useSelector((state) => state.order.allOrdersAddress);
  useEffect(() => {
    dispatch(getAllOrderAddress());
  }, [dispatch]);
  const {
    control,
    handleSubmit,
    register,
    reset,
    getValues,
    setValue,
    formState: { errors },
  } = useForm({
    defaultValues: {
      // name: details.name || "",
      // pincode: details.pincode || "",
      // addressLine1: details.addressLine1 || "",
      // addressLine2: details.addressLine2 || "",
      // landmark: details.landmark || "",
      // city: details.city || "",
      // country: details.country || null,
      // state: details.state || null,
      // defaultAddress: details.defaultAddress || false,
      // instructions: details.instructions || "",
      // contact: details.contact || "",
    },
  });

  const [isEdit, setIsEdit] = useState(false);

  const countries = useSelector((state) => state.master.all_country);
  const states = useSelector((state) => state.master.all_state);
  const cities = useSelector((state) => state.master.all_city);
  const pincodes = useSelector((state) => state.master.all_pincode);

  useEffect(() => {
    dispatch(getAllCountries());
  
  }, [dispatch]);

  const handleCountryChange = (selectedOption) => {
    setValue("country_id", selectedOption?.value);
    setValue("state_id", null);
    setValue("city_id", null);
    setValue("pincode_id", null);
    dispatch(AllState({ countryId: selectedOption.value }));
  };

  const handleStateChange = (selectedOption) => {
    setValue("state_id", selectedOption.value);
    setValue("city_id", null);
    setValue("pincode_id", null);
    dispatch(AllCity({ stateId: selectedOption.value }));
  };

  const handleCityChange = (selectedOption) => {
    setValue("city_id", selectedOption?.value);
    setValue("pincode_id", null);
    dispatch(AllPincode({ cityId: selectedOption.value }));
  };

  const handlePincodeChange = (selectedOption) => {
    setValue("pincode_id", selectedOption?.value);
  };

  const onSubmit = async (data) => {
    const DataToSend = new FormData();
    DataToSend.append("country_id", data?.country_id?.value);
    DataToSend.append("state_id", data?.state_id?.value);
    DataToSend.append("first_name", data?.name);
    DataToSend.append("pincode_id", data?.pincode_id?.value);
    DataToSend.append("street", data?.street);
    DataToSend.append("building", data?.building);
    DataToSend.append("city_id", data?.city_id?.value);
    DataToSend.append("contact_no", data?.contact_no);
    DataToSend.append("apartment", data?.landmark);
    const res = await dispatch(createOrderAddress({ data: DataToSend }));
    if (res.meta?.requestStatus === "fulfilled") {
      setShowSucsessModal(true);
      setTimeout(() => {
        setShowSucsessModal(false);
        reset({
          country_id: null,
          state_id: null,
          name: "",
          pincode_id: null,
          street: "",
          building: "",
          city_id: null,
          contact_no: "",
          landmark: "",
        });
        setIsEdit(false);
        reset();
      }, 3000);
    } else if (res.meta?.requestStatus === "rejected") {
    }
    setIsEdit(false);
    reset();
    await dispatch(getAllOrderAddress());
  };

  const [isUpdate, setIsUpdate] = useState(false);

  const [id, setId] = useState();

  const handleEdit = async (data) => {
    const res = await dispatch(getSingleOrderAddress({ id: data.id }));
    setId(data.id);
   
    // setValue("country_id", res.payload.data.country_id)
    reset(res.payload.data);
    setIsUpdate(true);
    setIsEdit(true);
  };

  

  const handleUpdate = async (data) => {
    const DataToSend = new FormData();
    DataToSend.append("country_id", data?.country_id?.value);
    DataToSend.append("state_id", data?.state_id?.value);
    DataToSend.append("first_name", data?.name);
    DataToSend.append("pincode_id", data?.pincode_id?.value);
    DataToSend.append("street", data?.street);
    DataToSend.append("building", data?.building);
    DataToSend.append("city_id", data?.city_id?.value);
    DataToSend.append("contact_no", data?.contact_no);
    DataToSend.append("apartment", data?.landmark);
    const res = await dispatch(EditOrderAddress({ id, data: DataToSend }));

    if (res.meta?.requestStatus === "fulfilled") {
      setShowSucsessModal(true);
    setShowSucsessModal(true);
      setTimeout(() => {
        setShowSucsessModal(false);
        setIsEdit(false);
        setIsUpdate(false);
        reset({
          country_id: null,
          state_id: null,
          name: "",
          pincode_id: null,
          street: "",
          building: "",
          city_id: null,
          contact_no: "",
          landmark: "",
        });
      }, 3000);
    } else if (res.meta?.requestStatus === "rejected") {
    }
    // setIsEdit(false);
    // reset();
  };

  const handleCancel = async () => {
    await dispatch(getAllOrderAddress());
    setIsEdit(false);
  };
  const handleDelete = async (id) => {
    await dispatch(deleteUserAddress(id));
    await dispatch(getAllOrderAddress());
  };

  const handleAdd = () => {
    setIsEdit(true);
    reset("");
  };

//   const blackStyles: StylesConfig<ColourOption> = {
//   control: (styles) => ({
//     ...styles,
//     backgroundColor: "#000",    
//     borderColor: "#444",
//     color: "#fff",
//   }),

//   menu: (styles) => ({
//     ...styles,
//     backgroundColor: "#000",     
//   }),

//   option: (styles, { isDisabled, isFocused, isSelected }) => {
//     return {
//       ...styles,
//       backgroundColor: isDisabled
//         ? undefined
//         : isSelected
//         ? "#111"     
//         : isFocused
//         ? "#222"     
//         : "#000",   

//       color: isDisabled
//         ? "#555"
//         : "#fff",    

//       cursor: isDisabled ? "not-allowed" : "pointer",

//       ":active": {
//         ...styles[":active"],
//         backgroundColor: !isDisabled
//           ? isSelected
//             ? "#111"
//             : "#333"    
//           : undefined,
//       },
//     };
//   },

//   singleValue: (styles) => ({
//     ...styles,
//     color: "#fff",   
//   }),

//   placeholder: (styles) => ({
//     ...styles,
//     color: "#777",   
//   }),

//   input: (styles) => ({
//     ...styles,
//     color: "#fff",
//   }),
// };


  return (
    <>
      {!isEdit && (
        <div className="add_address_radio_box">
          <h4 className="">Your Saved Address</h4>

          <Form>
            <div className="row">
              {/* Map saved addresses here instead of hardcoded */}
              {allAddress?.data?.map((val, index) => {
                const parts = [
                  val?.building,
                  val?.street,
                  val?.apartment,
                  val?.Users_Address_Detail?.Country?.name,
                  val?.Users_Address_Detail?.State?.name,
                  val?.Users_Address_Detail?.City?.name,
                  val?.Users_Address_Detail?.Pincode?.name,
                ];
                const fullAddress = parts.filter(Boolean).join(", ");
                return (
                  <div
                    className="col-lg-6 col-md-6 col-sm-6 mb-2"
                    key={val.id || index}
                  >
                    <div className="address_radio_box_holder">
                      <p className="address_text">{fullAddress}</p>
                      <div className="icons_holder">
                        <div
                          className="icon_holder"
                          onClick={() => {
                            handleEdit(val);
                          }}
                        >
                          <FontAwesomeIcon
                            icon={faPenToSquare}
                            className="edit_icon"
                          />
                        </div>
                        <div
                          className="icon_holder"
                          onClick={() => {
                            handleDelete(val.id);
                          }}
                        >
                          <FontAwesomeIcon
                            icon={faTrash}
                            className="delete_icon"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}

              {/* <div className="col-lg-6 col-md-6 col-sm-6 mb-2">
                <div className="address_radio_box_holder">
                  <p className="address_text">Near the Old Temple, Village Kothrud, Taluka Haveli, Pune District, Maharashtra 411038, India</p>
                  <div className="icons_holder">
                    <div className="icon_holder" onClick={handleEdit}>
                      <FontAwesomeIcon
                        icon={faPenToSquare}
                        className="edit_icon"
                      />
                    </div>
                    <div className="icon_holder">
                      <FontAwesomeIcon icon={faTrash} className="delete_icon" />
                    </div>
                  </div>
                </div>
              </div>*/}
            </div>

            <div className="form_footer">
              <p className="add_address_text" onClick={handleAdd}>
                Add Address
              </p>
            </div>
          </Form>
        </div>
      )}

      {isEdit && (
        <section className="Manage_Address">
          {/* <div className="icons_holder">
          <div className="icon_holder">
            <FontAwesomeIcon icon={faPenToSquare} className="edit_icon" />
          </div>

          <div className="icon_holder">
            <FontAwesomeIcon icon={faTrash} className="delete_icon" />
          </div>
        </div> */}

          <div className="personal_info_form">
            <Form>
              <div className="row">
                <div className="">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Full Name *</Form.Label>
                    <Form.Control
                      {...register("name", {
                        required: "Full name is required",
                      })}
                    />
                    {errors.name && (
                      <p className="error__feedback">{errors.name.message}</p>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Country / Region</Form.Label>
                    <Controller
                      className="Select_Dropdown_holder"
                      name="country_id" // Form field name
                      control={control}
                      rules={{ required: "Country is required" }}
                      render={({ field }) => (
                        // <Select
                        //   options={countries}
                        //   onChange={(val) => {
                        //     field.onChange(val);
                        //     handleCountryChange(val);
                        //   }}
                        //   placeholder="Country"
                        //   classNamePrefix="custom-select"
                        // />
                        <Select
                              styles={{
                            control: (baseStyles) => ({
                              ...baseStyles,
                              borderColor: errors.country_id
                                ? "red"
                                : baseStyles,
                            }),
                          }}
                          {...field}
                          options={countries}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            // GetAllStates(selectedOption.value);
                            handleCountryChange(selectedOption);
                            setValue("country_id", selectedOption);
                            // setValue("state_id", null);
                            // setValue("city_id", null);
                            // clearErrors("country_id");
                          }}
                        />
                      )}
                    />
                    {errors.country_id && (
                      <p className="error__feedback">
                        {errors.country_id.message}
                      </p>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>State</Form.Label>
                    <Controller
                      className="Select_Dropdown_holder"
                      name="state_id" // Form field name
                      control={control}
                      rules={{ required: "State is required" }}
                      render={({ field }) => (
                        // <Select
                        //   className="Select_Dropdown_holder__select"
                        //   classNamePrefix="custom-select"
                        //   placeholder="State"
                        //   options={states}

                        //   onChange={(val) => {
                        //     field.onChange(val); // update form
                        //     handleStateChange(val); // your custom logic
                        //   }}
                        // />
                        <Select
                          styles={{
                            control: (baseStyles) => ({
                              ...baseStyles,
                              borderColor: errors.country_id
                                ? "red"
                                : baseStyles,
                            }),
                          }}
                          {...field}
                          options={states}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handleStateChange(selectedOption);
                            setValue("state_id", selectedOption);
                            setValue("city_id", null);
                            // clearErrors("country_id");
                          }}
                        />
                      )}
                    />
                    {errors.state_id && (
                      <p className="error__feedback">
                        {errors.state_id.message}
                      </p>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>City</Form.Label>
                    <Controller
                      className="Select_Dropdown_holder"
                      name="city_id" // Form field name
                      control={control}
                      rules={{ required: "City is required" }}
                      render={({ field }) => (
                        // <Select
                        //   styles={{
                        //     control: (baseStyles) => ({
                        //       ...baseStyles,
                        //       borderColor: errors.country_id
                        //         ? "red"
                        //         : baseStyles,
                        //     }),
                        //   }}
                        //   {...field}
                        //   options={cities}
                        //   onChange={(selectedOption) => {
                        //     field.onChange(selectedOption.value); // Update Controller's value
                        //     // GetAllStates(selectedOption.value);
                        //     handleCityChange(selectedOption);
                        //     // clearErrors("country_id");
                        //   }}
                        // />

                        <Select
                          styles={{
                            control: (baseStyles) => ({
                              ...baseStyles,
                              borderColor: errors.country_id
                                ? "red"
                                : baseStyles,
                            }),
                          }}
                          {...field}
                          options={cities}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handleCityChange(selectedOption);
                            setValue("city_id", selectedOption);
                            // setValue("city_id", null);
                            // clearErrors("country_id");
                          }}
                        />
                      )}
                    />
                    {errors.city_id && (
                      <p className="error__feedback">
                        {errors.city_id.message}
                      </p>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Pincode</Form.Label>
                    <Controller
                      className="Select_Dropdown_holder"
                      name="pincode_id" // Form field name
                      control={control}
                      rules={{ required: "Pincode is required" }}
                      render={({ field }) => (
                        <Select
                          styles={{
                            control: (baseStyles) => ({
                              ...baseStyles,
                              borderColor: errors.country_id
                                ? "red"
                                : baseStyles,
                            }),
                          }}
                          {...field}
                          options={pincodes}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handlePincodeChange(selectedOption);

                            setValue("pincode_id", selectedOption);
                          }}
                        />
                      )}
                    />
                    {errors.pincode_id && (
                      <p className="error__feedback">
                        {errors.pincode_id.message}
                      </p>
                    )}
                  </Form.Group>
                </div>

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Contact *</Form.Label>
                    <Controller
                      name="contact_no"
                      control={control}
                      rules={{ required: "Contact is required" }}
                      render={({ field }) => (
                        <PhoneInput
                          {...field}
                          country="in"
                          onChange={(value) => field.onChange(value)}
                          inputClass="form-control"
                        />
                      )}
                    />
                    {errors.contact_no && (
                      <p className="error__feedback">
                        {errors.contact_no.message}
                      </p>
                    )}
                  </Form.Group>
                </div>

                <div className="">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>
                      Flat, House No., Building, Company, Apartment
                    </Form.Label>
                    <Form.Control
                      {...register("building", {
                        required: "Address line is required",
                      })}
                    />
                    {errors.building && (
                      <p className="error__feedback">
                        {errors.building.message}
                      </p>
                    )}
                  </Form.Group>
                </div>

                <div className="">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Area, Street, Sector, Village</Form.Label>
                    <Form.Control
                      type="text"
                      name="street"
                      placeholder="Enter Address"
                      {...register("street")}
                    />
                  </Form.Group>
                </div>

                <div className="">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Landmark</Form.Label>
                    <Form.Control
                      type="text"
                      name="landmark"
                      placeholder="Enter Address"
                      {...register("landmark")}
                    />
                  </Form.Group>
                </div>

                {/* 
              <div className="">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                >
                  <Form.Check
                    type="checkbox"
                    label="Make this my default address"
                    name="timeframe"
                    value="Male"
                    className="custom-radio-green"
                  />
                </Form.Group>
              </div> */}

                <div className="form_footer">
                  <div className="btns_holder">
                    {isUpdate ? (
                      <div className="save_btn me-2">
                        <Green_btn
                          btnText="Update"
                          onClick={handleSubmit(handleUpdate)}
                        />
                      </div>
                    ) : (
                      <div className="save_btn me-2">
                        <Green_btn
                          btnText="Save"
                          onClick={handleSubmit(onSubmit)}
                        />
                      </div>
                    )}

                    <div className="cancel_btn me-2">
                      <Green_round_btn
                        btnText="Cancel"
                        onClick={handleCancel}
                      />
                    </div>
                  </div>

                  {/* <p className="add_address_text">Add Address</p> */}
                </div>
              </div>
            </Form>
          </div>
        </section>
      )}
      <Success_Modal
        show={showSuccessModal}
        onHide={() => {
          setShowSucsessModal(false);
        }}
        successText={
          isEdit ? "Address Updated Suceesfully!" : "Address Added Suceesfully!"
        }
      />
    </>
  );
};

export default Manage_Address;
