"use client";

import AppContext from "@ctx/AppContext";
import { iranCities } from "iranCities";
import { iranProvince } from "iranProvince";
import Chapar from "plugins/Chapar";
import validateIranPhone from "plugins/IranPhoneRegex";
import { useContext, useEffect, useRef, useState } from "react";
import { BottomSheet } from "react-spring-bottom-sheet";
import { toast } from "react-toastify";
import SimpleReactValidator from "simple-react-validator";

const BottomSheetAddress = () => {
  const CTX = useContext(AppContext);
  const provinceData = iranProvince();
  const citiesData = iranCities();

  const [province, setProvince] = useState(null);
  const [city, setCity] = useState(null);
  const [cityData, setCityData] = useState([]);
  const [plaque, setPlaque] = useState("");
  const [address, setAddress] = useState("");
  const [buildingUnit, setBuildingUnit] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [receiverFullName, setReceiverFullName] = useState("");
  const [receiverPhoneNumber, setReceiverPhoneNumber] = useState("");

  const validator = useRef(
    new SimpleReactValidator({
      messages: {
        required: "پر کردن این فیلد الزامی میباشد",
      },
      element: (message) => (
        <>
          <div className="text-right px-1 ">
            <small className="text-red-600 t-ig-small  ">{message}</small>
          </div>
        </>
      ),
    })
  );

  const body = {
    address,
    province: provinceData?.find((e) => e.id == province)?.title,
    city: citiesData?.find((e) => e.id == city)?.title,
    plaque,
    buildingUnit,
    receiverFullName,
    receiverPhoneNumber,
    postalCode,
  };

  const handleCreateAddress = async () => {
    if (validateIranPhone(receiverPhoneNumber)) {
      if (validator.current.allValid()) {
        try {
          const data = await Chapar.post(
            `${process.env.NEXT_PUBLIC_API_URL}/user/address`,
            JSON.stringify(body),
            {
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            }
          );

          toast.success(`آدرس اضافه شد`, {
            position: "bottom-right",
            closeOnClick: true,
          });

          CTX.setBottomSheetAddressOpen(false);
          CTX.fetchAddressUser();
        } catch ({ error, status }) {
          toast.error(`${error?.response?.data?.message}`, {
            position: "bottom-right",
            closeOnClick: true,
          });
        }
      } else {
        toast.error("پرکردن همه ی فیلد ها واجب است", {
          position: "bottom-right",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } else {
      toast.error("شماره تماس را درست وارد کنید", {
        position: "bottom-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  useEffect(() => {
    setCityData(citiesData.filter((city) => city.province_id == province));
  }, [province]);

  return (
    <BottomSheet
      open={CTX.state.bottomSheetAddressOpen}
      onDismiss={() => CTX.setBottomSheetAddressOpen(false)}
      className={"z-50 relative "}
    >
      <div className="xs:w-full lg:w-4/12 mx-auto">
        <div className="text-center p-3">
          <p className="mb-0 text-sm  pb-3">اقزودن آدرس جدید </p>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            استان
            <small className="text-red-500 mx-1">*</small>
          </label>

          <select
            type="text"
            name="province"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="نام استان"
            onChange={(e) => {
              setProvince(e.target.value);
              validator.current.showMessageFor("province");
            }}
            defaultValue=""
          >
            <option value="" disabled hidden>
              انتخاب کنید
            </option>
            {provinceData?.map((c, index) => (
              <option key={index} value={c.id}>
                {c.title}
              </option>
            ))}
          </select>

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>
                  {validator.current.message("province", province, "required")}
                </>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            شهر
            <small className="text-red-500 mx-1">*</small>
          </label>

          <select
            type="text"
            name="city"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="نام استان"
            onChange={(e) => {
              setCity(e.target.value);
              validator.current.showMessageFor("city");
            }}
          >
            {cityData?.map((c, index) => (
              <option key={index} value={c.id}>
                {c.title}
              </option>
            ))}
          </select>
          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>{validator.current.message("city", city, "required")}</>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            آدرس
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="address"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="اسم محله , خیابان , کوچه"
            onChange={(e) => {
              setAddress(e.target.value);
              validator.current.showMessageFor("address");
            }}
          />
          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>{validator.current.message("address", address, "required")}</>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            پلاک
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="plaque"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder=" 10"
            onChange={(e) => {
              setPlaque(e.target.value);
              validator.current.showMessageFor("plaque");
            }}
          />

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>{validator.current.message("plaque", plaque, "required")}</>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            واحد
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="buildingUnit"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="2"
            onChange={(e) => {
              setBuildingUnit(e.target.value);
              validator.current.showMessageFor("buildingUnit");
            }}
          />

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>
                  {validator.current.message(
                    "buildingUnit",
                    buildingUnit,
                    "required"
                  )}
                </>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            کد پستی
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="postalCode"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="2"
            onChange={(e) => {
              setPostalCode(e.target.value);
              validator.current.showMessageFor("postalCode");
            }}
          />

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>
                  {validator.current.message(
                    "postalCode",
                    postalCode,
                    "required"
                  )}
                </>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            نام گرینده
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="receiverFullName"
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="علی احمدی"
            onChange={(e) => {
              setReceiverFullName(e.target.value);
              validator.current.showMessageFor("receiverFullName");
            }}
          />

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>
                  {validator.current.message(
                    "receiverFullName",
                    receiverFullName,
                    "required"
                  )}
                </>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="p-3">
          <label className="float-right mx-3 text-sm my-2 rtl">
            شماره گرینده
            <small className="text-red-500 mx-1">*</small>
          </label>

          <input
            type="text"
            name="receiverPhoneNumber"
            onChange={(e) => {
              setReceiverPhoneNumber(e.target.value);
              validator.current.showMessageFor("receiverPhoneNumber");
            }}
            className="form-control  bg-white !border-[1px] focus:!border-[1px]  border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03   "
            placeholder="0912......"
          />

          <div className="flex justify-start w-full">
            <small className=" ">
              {" "}
              {validator ? (
                <>
                  {validator.current.message(
                    "receiverPhoneNumber",
                    receiverPhoneNumber,
                    "required"
                  )}
                </>
              ) : (
                ""
              )}
            </small>
          </div>
        </div>

        <div className="w-full p-3 ">
          <button
            className="btn btn-primary text-sm w-full py-3 rounded-3xl"
            onClick={() => handleCreateAddress()}
          >
            ساخت آدرس جدید{" "}
          </button>
        </div>
      </div>
    </BottomSheet>
  );
};

export default BottomSheetAddress;
