import React, { useContext, useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import CheckoutStepFormContext from "../CheckoutStepFormContext";
import Green_Outline_Btn from "../../../common-components/common_btn/green_outline_btn/Green_Outline_Btn";
import { Form, Modal } from "react-bootstrap";
import Select from "react-select";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faAngleDown,
  faAngleUp,
  faPenToSquare,
  faTrash,
} from "@fortawesome/free-solid-svg-icons";
import {
  AllCity,
  AllPincode,
  AllState,
  getAllCountries,
} from "../../../../features/master/masterSlice";
import { useDispatch, useSelector } from "react-redux";
import {
  createOrderAddress,
  EditOrderAddress,
  getAllOrderAddress,
  getSingleOrderAddress,
} from "../../../../features/order/orderSlice";

import { deleteUserAddress } from "../../../../features/user/userSlice";
import { useRouter } from "next/navigation";

const Details = ({ selectedAddressId, setSelectedAddressId }) => {
  const { next } = useContext(CheckoutStepFormContext);
  const [showTextarea, setShowTextarea] = useState(false);
  const [showAddressModal, setShowAddressModal] = useState(false);
  const {
    control,
    handleSubmit,
    register,
    getValues,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    defaultValues: {},
  });

  const current_location = useSelector(
    (state) => state.location.current_location,
  );

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

  const dispatch = useDispatch();
  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) => {
    setAddressError("");
    const DataToSend = new FormData();
    DataToSend.append("lat", current_location?.geometry?.location?.lat);
    DataToSend.append("long", current_location?.geometry?.location?.long);
    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);
    DataToSend.append("delivery_instruction", data?.delivery_instruction);
    const res = await dispatch(createOrderAddress({ data: DataToSend }));

    if (res.meta?.requestStatus === "fulfilled") {
      setIsEdit(false);
      reset();
      await setSelectedAddressId(res.payload?.data?.id);
      await dispatch(getAllOrderAddress());

      next();
    } else if (res.meta?.requestStatus === "rejected") {
    }
  };

  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);
    DataToSend.append("delivery_instruction", data?.delivery_instruction);
    const res = await dispatch(EditOrderAddress({ id, data: DataToSend }));

    if (res.meta?.requestStatus === "fulfilled") {
      dispatch(getAllOrderAddress());
    } else if (res.meta?.requestStatus === "rejected") {
    }
    setIsEdit(false);
    reset();
  };
  const [isEdit, setIsEdit] = useState(false);
  const [isUpdate, setIsUpdate] = useState(false);

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

  useEffect(() => {
    dispatch(getAllOrderAddress());
    if (allAddress?.data?.length > 0) {
      setSelectedAddressId(allAddress.data[0].id);
    }
  }, [dispatch]);

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

  const [id, setId] = useState();

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

  const handleAdd = () => {
    setShowAddressModal(true);
    setIsEdit(true);
    reset("");
    setAddressError("");
  };
  const handleCancel = async () => {
    await dispatch(getAllOrderAddress());
    setShowAddressModal(true);
    setIsEdit(false);
  };

  const [addressError, setAddressError] = useState("");

  const handleNext = () => {
    if (allAddress?.data?.length > 0) {
      setAddressError(""); // Clear error
      next(); // Proceed
    } else {
      setAddressError("Please add an address before continuing.");
    }
  };

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

  const navigate = useRouter();

  useEffect(() => {
    if (!isUpdate && current_location?.formatted_address) {
      setValue("street", current_location.formatted_address, {
        shouldValidate: true,
        shouldDirty: true,
      });
    }
  }, [current_location, setValue]);

  console.log(
    current_location?.formatted_address,
    "current_location?.formatted_address  current_location current_location",
  );

  return (
    <>
      <div className="add_address_radio_box">
        <h4>Your Saved Address</h4>

        <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-4 col-lg-6 col-md-6 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">
                      <FontAwesomeIcon
                        icon={faPenToSquare}
                        className="edit_icon"
                        onClick={() => {
                          handleEdit(val);
                        }}
                      />
                    </div>
                    <div className="icon_holder">
                      <FontAwesomeIcon
                        icon={faTrash}
                        className="delete_icon"
                        onClick={() => {
                          handleDelete(val.id);
                        }}
                      />
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="form_footer">
          <p className="add_address_text" onClick={handleAdd}>
            Add Address
          </p>
        </div>
      </div>
      <Modal
        show={showAddressModal}
        onHide={() => {
          setShowAddressModal(false);
          setIsEdit(false);
        }}
        size="lg"
        centered
        className="AddressModal"
      >
        <Modal.Header closeButton>
          <Modal.Title>Add Address</Modal.Title>
        </Modal.Header>

        <Modal.Body>
          <section className="Manage_Address">
            <>
              <Form className="details__wrapper">
                <div className="row">
                  <div className="col-12">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.name ? "input__error" : ""
                      }`}
                    >
                      <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-md-6">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.country ? "input__error" : ""
                      }`}
                    >
                      <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
                            className="common_select"
                            classNamePrefix="common_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);
                            }}
                          />
                        )}
                      />
                      {errors.country_id && (
                        <p className="error__feedback">
                          {errors.country_id.message}
                        </p>
                      )}
                    </Form.Group>
                  </div>
                  <div className="col-md-6">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.state ? "input__error" : ""
                      }`}
                    >
                      <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="common_select"
                            classNamePrefix="common_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-md-6">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.city ? "input__error" : ""
                      }`}
                    >
                      <Form.Label>Town / City *</Form.Label>
                      <Controller
                        className="Select_Dropdown_holder"
                        name="city_id" // Form field name
                        control={control}
                        rules={{ required: "City is required" }}
                        render={({ field }) => (
                          <Select
                            className="common_select"
                            classNamePrefix="common_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-md-6">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.pincode ? "input__error" : ""
                      }`}
                    >
                      <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
                            className="common_select"
                            classNamePrefix="common_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-lg-6">
                    <Form.Group className="form__item input_group">
                      <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="col-lg-6">
                    <Form.Group
                      className={`form__item input_group ${
                        errors.addressLine1 ? "input__error" : ""
                      }`}
                    >
                      <Form.Label>
                        Flat, House No., Building, Company *
                      </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="col-lg-6">
                    <Form.Group className="form__item input_group">
                      <Form.Label>Area, Street, Sector, Village</Form.Label>
                      <Form.Control {...register("street")} />
                    </Form.Group>
                  </div>

                  <div className="col-lg-6">
                    <Form.Group className="form__item input_group">
                      <Form.Label>Landmark</Form.Label>
                      <Form.Control {...register("landmark")} />
                    </Form.Group>
                  </div>

                  <div className="col-12">
                    <Form.Group className="input_group">
                      <Form.Label>Delivery Instructions (Optional)</Form.Label>
                      <div
                        onClick={() => setShowTextarea(!showTextarea)}
                        style={{ cursor: "pointer" }}
                      >
                        <span className="note__text">
                          Add Preferences, Notes, Access Codes And More{" "}
                          <FontAwesomeIcon
                            className="text-muted"
                            icon={showTextarea ? faAngleUp : faAngleDown}
                          />
                        </span>
                      </div>

                      {showTextarea && (
                        <Form.Control
                          as="textarea"
                          rows={2}
                          {...register("delivery_instruction")}
                        />
                      )}
                    </Form.Group>
                  </div>
                </div>

                <div className="form__item button__items d-flex justify-content-center gap-2">
                  <Green_Outline_Btn
                    // btnText="Next"
                    btnText="Cancel"
                    onClick={() => handleCancel()}
                    // onClick={() => next()}
                  />{" "}
                  {isUpdate ? (
                    <Green_Outline_Btn
                      btnText="Update"
                      onClick={handleSubmit(handleUpdate)}
                    />
                  ) : (
                    <Green_Outline_Btn
                      btnText="Save & Next"
                      // btnText="Save & Next"
                      onClick={handleSubmit(onSubmit)}
                    />
                  )}
                </div>
              </Form>
            </>
          </section>
        </Modal.Body>
      </Modal>
      {!isEdit && (
        <div className="form__item button__items d-flex justify-content-center align-items-center mb-3">
          <Green_Outline_Btn
            btnText="Back"
            onClick={() => navigate.push("/product-cart")}
          />
          <Green_Outline_Btn btnText="Next" onClick={handleNext} />
          {addressError && <p className="text-danger mt-2">{addressError}</p>}
        </div>
      )}
    </>
  );
};

export default Details;
