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,
  getAllOrderAddress,
} from "../../../../features/order/orderSlice";
import { createUserAddress, deleteUserAddress, getUserAddresses } from "../../../../features/user/userSlice";

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

  const {
    control,
    handleSubmit,
    register,
    getValues, reset,
    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 dispatch = useDispatch();


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


  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 (d) => {
    const res = await dispatch(createUserAddress(d));
    if (res.meta?.requestStatus === "fulfilled") {
    } else if (res.meta?.requestStatus === "rejected") {
    }
    reset()
  };

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

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

  const handleEdit = (data) => {
    setIsFormVisible(true);
    setValue("name", data?.name);
    setValue("country_id", data?.country_id);
    setValue("state_id", data?.state_id);
    setValue("city_id", data?.city_id);
    setValue("pincode_id", data?.pincode_id);
    setValue("street", data?.street);
    setValue("contact_no", data?.contact_no);
    setValue("landmark", data?.landmark);
  };

  const handleCancel = () => {
    setIsEdit(false);
  };

  const handleDelete = (id) => {
    // dispatch(deleteUserAddress(id));
  }

  const allAddress = useSelector((state) => state.order.allOrdersAddress);

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

  const [selectedAddressId, setSelectedAddressId] = useState();

  // useEffect(() => {
  //   if (selectedAddressId) {
  //     setSelectedAddressId(selectedAddressId);
  //   } else
  //     if (allAddress?.data?.length && !selectedAddressId) {
  //       setSelectedAddressId(allAddress.data[0].id);
  //     }

  //     setIsFormVisible(false)
  // }, [allAddress?.data]);

  return (
    <>

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

          <Form>
            <div className="row">
              {/* Map saved addresses here instead of hardcoded */}
              <div className="row">
                {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-xl-5 col-lg-6 col-md-12 col-sm-12 mb-2"
                      key={val.id || index}
                    >
                      <div className="address_radio_box_holder">
                        <Form.Check
                          inline
                          label={fullAddress}
                          name="group1"
                          type="radio"
                          value={val.id}
                          checked={selectedAddressId === val.id}
                          onChange={() => setSelectedAddressId(val.id)}
                        />
                        <div className="icons_holder">
                          <div className="icon_holder" onClick={handleEdit(val)}>
                            <FontAwesomeIcon icon={faPenToSquare} className="edit_icon" />
                          </div>

                          <div className="icon_holder" onClick={handleDelete(selectedAddressId)}>
                            <FontAwesomeIcon icon={faTrash} className="delete_icon" />
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}

                {/* <div className="col-xl-5 col-lg-6 col-md-12 col-sm-12 mb-2">
                          <div className="address_radio_box_holder">
                            <Form.Check
                              inline
                              label="Flat No. 502, Orchid Towers Koregaon Park Road Pune, Maharashtra 411001 India"
                              name="group1"
                              type="radio"
                            />
                          </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 Personal_Info">
        {/* <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"
                      />
                    )}
                  />
                  {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
                        options={states}
                        onChange={(val) => {
                          field.onChange(val);
                          handleStateChange(val);
                        }}
                        placeholder="State"
                        classNamePrefix="custom-select"
                      />
                    )}
                  />
                  {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
                        options={cities}
                        onChange={(val) => {
                          field.onChange(val);
                          handleCityChange(val);
                        }}
                        placeholder="State"
                        classNamePrefix="custom-select"
                      />
                    )}
                  />
                  {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
                        options={pincodes}
                        onChange={(val) => {
                          field.onChange(val);
                          handlePincodeChange(val);
                        }}
                        placeholder="Pincode"
                        classNamePrefix="custom-select"
                      />
                    )}
                  />
                  {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">
                  <div className="save_btn">
                    <Green_btn
                      btnText="Save"
                      onClick={handleSubmit(onSubmit)}
                    />
                  </div>
                  <div className="cancel_btn">
                    <Green_round_btn
                      btnText="Cancel"
                      onClick={handleCancel}
                    />
                  </div>
                </div>

                {/* <p className="add_address_text">Add Address</p> */}
              </div>
            </div>
          </Form>
        </div>
      </section>
      )}
    </>
  );
};

export default Manage_Address;
