"use client";
import { RootState } from "@/store/store";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/store/store";
import {
  CancelAddOrUpdateAddresses,
  DeleteAddress,
  getAddressById,
  ToggleDefaultAddress,
} from "@/store/address.slice";
import { Addresses, AuthStage } from "@/interfaces/types";
import axiosInstanceClient from "@/utils/axiosClient";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { clearLocation, setLocation } from "@/store/location.slice";
import showAlert from "@/shared/ShowAlert";
import { useTranslations } from "next-intl";
import { UpdateProfile } from "@/utils/helpers";

export default function PersonalAccountAddresses({
  setIsOpen,
  setAuthStage,
}: {
  setIsOpen: (value: boolean) => void;
  setAuthStage: (value: AuthStage) => void;
}) {
  const t = useTranslations();

  const dispatch = useDispatch<AppDispatch>();

  const EditItem = async (id: string) => {
    dispatch(getAddressById({ id })).then((res) => {
      if (res.payload) {
        setIsOpen(true);
        setAuthStage("location");
      }
    });
  };
  const deleteItemFromAddress = async (address: Addresses) => {
    await axiosInstanceClient
      .delete(`client/addresses/${address?.id}`)
      .then((res: any) => {
        ShowAlertMixin({
          icon: "success",
          title: res?.data?.message,
        });
        dispatch(DeleteAddress({ id: address?.id }));
        if (+address?.is_default == 1) {
          dispatch(clearLocation());
          UpdateProfile({ dispatch });
        }
      })
      .catch((error) => {
        const errorMessage = error?.message;
        ShowAlertMixin({
          icon: "error",
          title: errorMessage,
        });
      });
  };
  const deleteItem = (address: Addresses) => {
    showAlert({
      t,
      title: t("Text.deleteAddress"),
      text: t("Text.deleteAddressDesc"),
      action: () => deleteItemFromAddress(address),
    });
  };
  const toggleItemToDefault = async (address: Addresses) => {
    const id = address?.id;
    await axiosInstanceClient
      .post(`client/addresses/${id}/toggle-default`)
      .then((res) => {
        ShowAlertMixin({
          icon: "success",
          title: res?.data?.message,
        });
        if (+address?.is_default == 1) {
          dispatch(clearLocation());
          UpdateProfile({ dispatch });
        } else {
          dispatch(
            setLocation({
              id: address?.id,
              is_default: true,
              phone_code: address?.contact?.phone_code,
              phone: address?.contact?.phone,
              country: address?.location?.country,
              city: address?.location?.city,
              lng: address?.location?.longitude?.toString(),
              lat: address?.location?.latitude?.toString(),
              description: address?.description,
              district: address?.location?.district,
              isLoading: false,
            }),
          );
        }
        dispatch(ToggleDefaultAddress({ id: id }));
      })
      .catch((error) => {
        const errorMessage = error?.message;
        ShowAlertMixin({
          icon: "error",
          title: errorMessage,
        });
      });
  };
  const { allAddressesItems } = useSelector(
    (state: RootState) => state.AddressConfig,
  );
  return (
    <div className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 lg:p-8 p-4">
      <h3 className="text-xl mb-6"> {t("LABELS.manage_addresses")} </h3>
      <div className="space-y-4">
        <button
          onClick={() => {
            setIsOpen(true);
            setAuthStage("location");
            dispatch(CancelAddOrUpdateAddresses());
          }}
          type="button"
          className="bg-primary cursor-pointer border border-gray-200 text-white text-base px-8 py-3.5 rounded-lg font-medium shadow-sm transition-all duration-300 flex items-center gap-2 group"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="lucide lucide-plus ms-2 *:stroke-white"
          >
            <path d="M5 12h14"></path>
            <path d="M12 5v14"></path>
          </svg>
          {t("BUTTONS.addNewAddress")}
        </button>

        <div className="space-y-4">
          {allAddressesItems?.map((address, index) => (
            <div
              key={index}
              className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 lg:p-8 p-4"
            >
              <div className="flex lg:flex-row flex-col lg:justify-between items-center my-2">
                <h4 className="text-xl mb-4">{t("Text.locationDetails")}</h4>
                <div className="flex gap-2">
                  <button
                    onClick={() => EditItem(address?.id)}
                    type="button"
                    className="bg-transparent cursor-pointer border border-gray-200 text-text-primary text-base px-8 py-3.5 rounded-lg font-medium shadow-sm transition-all duration-300 flex items-center gap-2 group"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="lucide lucide-pen"
                    >
                      <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"></path>
                    </svg>
                  </button>
                  <button
                    onClick={() => deleteItem(address)}
                    type="button"
                    className="bg-transparent cursor-pointer border border-gray-200 text-text-primary text-base px-8 py-3.5 rounded-lg font-medium shadow-sm transition-all duration-300 flex items-center gap-2 group"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="lucide lucide-trash2 lucide-trash-2"
                    >
                      <path d="M3 6h18"></path>
                      <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
                      <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
                      <line x1="10" x2="10" y1="11" y2="17"></line>
                      <line x1="14" x2="14" y1="11" y2="17"></line>
                    </svg>
                  </button>
                  <button
                    onClick={() => toggleItemToDefault(address)}
                    disabled={+address?.is_default == 1 ? true : false}
                    type="button"
                    className={`${+address?.is_default == 0 ? "bg-white text-text-primary" : "bg-primary text-text-primary"} cursor-pointer border border-gray-200  text-base px-8 py-3.5 rounded-lg font-medium shadow-sm transition-all duration-300 flex items-center gap-2 group`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className={`lucide lucide-house ${+address?.is_default == 0 ? "*:stroke-text-primary" : "*:stroke-white"}`}
                    >
                      <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"></path>
                      <path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                    </svg>
                  </button>
                </div>
              </div>
              <div className="space-y-2">
                <p className="text-sm text-text-secondary">
                  {t("LABELS.country")}: {address?.location?.country?.name}
                </p>
                <p className="text-sm text-text-secondary">
                  {t("LABELS.city")}: {address?.location?.city?.name}
                </p>
                <p className="text-sm text-text-secondary">
                  {t("LABELS.district")}: {address?.location?.district?.name}
                </p>

                <p className="text-sm text-text-secondary">
                  {t("LABELS.location_description")}:{address?.description}
                </p>
                {/* <p className="text-sm text-text-secondary">المبنى: مبنى 123</p> */}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
