"use client";
import React from "react";
import { FaPlus } from "react-icons/fa";
import { useTranslations } from "next-intl";
import showAlert from "@/shared/ShowAlert";
import axiosInstance from "@/utils/axiosClient";
import { useDispatch } from "react-redux";
import {
  getAddressById,
  CancelAddOrUpdateAddresses,
  DeleteAddress,
  ToggleDefaultAddress,
} from "@/store/address.slice";
import { AppDispatch } from "@/store/store";
import AddressCard from "@/shared/card/AddressCard";
import { clearLocation, setLocation } from "@/store/location.slice";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { Addresses } from "@/interfaces/types";
import { AuthStage } from "@/interfaces/types";

type Props = {
  addresses: Addresses[];
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  setAuthStage: React.Dispatch<React.SetStateAction<AuthStage>>;
};

export default function AddressesDetials({
  setAuthStage,
  addresses,
  setIsOpen,
}: Props) {
  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: any) => {
    await axiosInstance
      .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());
      })
      .catch((error) => {
        const errorMessage = error?.message;
        ShowAlertMixin({
          icon: "error",
          title: errorMessage,
        });
      });
  };
  const deleteItem = (address: any) => {
    showAlert({
      t,
      title: t("Text.deleteAddress"),
      text: t("Text.deleteAddressDesc"),
      action: () => deleteItemFromAddress(address),
    });
  };
  const toggleItemToDefault = async (address: any) => {
    const id = address?.id;
    await axiosInstance
      .post(`client/addresses/${id}/toggle-default`)
      .then((res) => {
        ShowAlertMixin({
          icon: "success",
          title: res?.data?.message,
        });
        if (+address?.is_default == 1) {
          dispatch(clearLocation());
        } 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,
              lat: address?.location?.latitude,
              description: address?.description,
              district: address?.location?.district,
              isLoading: false,
            }),
          );
        }
        dispatch(ToggleDefaultAddress({ id: id }));
      })
      .catch((error) => {
        const errorMessage = error?.message;
        ShowAlertMixin({
          icon: "error",
          title: errorMessage,
        });
      });
  };
  return (
    <div className="bg-greynormal p-6 rounded-2xl border border-primary-light">
      <div className="flex sm:flex-row flex-col gap-4 sm:items-center my-6">
        <h2 className="flex-1 text-primary-dark font-medium lg:text-2xl md:text-lg text-base text-start lg:leading-[50px]   leading-8">
          {t("Text.addressesTitle")}
        </h2>
        <button
          onClick={() => {
            setIsOpen(true);
            setAuthStage("location");
            dispatch(CancelAddOrUpdateAddresses());
          }}
          className="text-center cursor-pointer  grid grid-cols-[auto_1fr] items-center gap-2 px-7 py-3 bg-primary text-white font-medium rounded-full "
        >
          <FaPlus size={25} />
          <p className="lg:text-lg text-base font-medium">
            {t("BUTTONS.addNewAddress")}
          </p>
        </button>
      </div>
      <div className="grid gap-2">
        {addresses.map((address, index: number) => {
          return (
            <React.Fragment key={index}>
              <AddressCard
                setDefault={() =>
                  !address?.is_default && toggleItemToDefault(address)
                }
                EditItem={() => EditItem(address?.id)}
                deleteItem={() => deleteItem(address)}
                address={address}
              />
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}
