"use client";
import ImageWithFallback from "@/components/UiComponents/ImageWithFallback";
import AppTable from "@/components/UiComponents/table/AppTable";
import { FailedIcon, SuccessIcon, ViewIcon } from "@/assets/svgs/TraderIcons";
import { useTranslations } from "next-intl";
import { useState, useEffect } from "react";
import AppModal from "@/components/UiComponents/Modal/AppModal";
import axiosInstance from "@/services/axiosClient";
import toast from "react-hot-toast";
import { showDynamicSwal } from "@/utils/helpers";
import Success from "@/assets/images/success2.gif";

interface Props {
  items: any[];
}
const ReturnProductsTable = ({ items }: Props) => {
  const t = useTranslations();
  const [localItems, setLocalItems] = useState(items);

  useEffect(() => {
    setLocalItems(items);
  }, [items]);

  const ChangeStatus = async (status: "accept" | "reject", item_id: string) => {
    try {
      const confirm = await showDynamicSwal({
        title: status == "accept" ? t("Text.return_product") : t("Text.cancel_order"),
        text: status == "accept" ? t("Text.return_product_desc") : t("Text.cancel_order_desc"),
        confirmButtonText: t("buttons.ok"),
        cancelButtonText: t("buttons.noKeepMe"),
        customClass: {
          icon: "hidden-icon",
          title: "swal-title",
          confirmButton: "app-btn alert-btn",
          cancelButton: "app-btn outline-btn",
        },
      });

      if (confirm.isConfirmed) {
        const { data } = await axiosInstance.patch(`/my-returns/${item_id}`, { status });

        if (data) {
          await showDynamicSwal({
            title: status == "accept" ? t("orders.accept_order") : t("orders.cancel_order"),
            imageUrl: `${Success.src}`,
            text: "",
            showCancelButton: false,
            showConfirmButton: false,
            timer: 1500,
            customClass: {
              title: "swal-title",
              text: "hidden",
              confirmButton: "app-btn",
            },
          });

          setLocalItems((prev) =>
            prev.map((item) =>
              item.id === item_id ? { ...item, status: status } : item
            )
          );
        }
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message || "Error occurred");
    }
  };

  const [openModal, setOpenModal] = useState(false);

  const [selectedItem, setSelectedItem] = useState({
    reason: "",
    reason_image: "",
  });

  const handleSelectItem = (item: any) => {
    setOpenModal(true);
    setSelectedItem({
      reason: item?.reason,
      reason_image: item?.retrun_image,
    });
  };

  const columns = [
    {
      title: t("tables.product"),
      dataIndex: "product",
      key: "product",
      render: (_: any, record: any) => {
        const nameParts = record.name?.split("-") || [];
        const name = nameParts[0] || "";
        const features = [nameParts[1], nameParts[2]].filter(Boolean).join(", ");

        return (
          <div className="flex items-center gap-2">
            <ImageWithFallback
              src={record.main}
              width={80}
              height={80}
              alt={`product-name`}
              className="size-14 object-contain bg-greynormal"
            />
            <div className="text-xs">
              <h5 className="mb-2">{name}</h5>
              <p className="text-gray-500">{features}</p>
            </div>
          </div>
        );
      },
    },
    {
      title: t("tables.returnReason"),
      key: "action",
      render: (_: any, record: any) => (
        <button
          onClick={() => handleSelectItem(record)}
          className="border inline-flex items-center justify-center border-platinum rounded-xl p-2"
        >
          <ViewIcon className="size-6" />
        </button>
      ),
      align: "center",
    },
    {
      title: t("tables.quantity"),
      dataIndex: "quantity",
      key: "quantity",
    },
    {
      title: t("tables.refund_amount"),
      dataIndex: "refund_amount",
      key: "refund_amount",
      render: (refund_amount: string) => (
        <span>
          {refund_amount} {t("Text.IQ")}
        </span>
      ),
    },
    // {
    //   title: t("tables.total"),
    //   dataIndex: "total",
    //   key: "total",
    //   render: (_: any,record:any) => (
    //     <span>
    //       {Number(+record?.refund_amount * +record?.quantity).toFixed(3)} {t("Text.IQ")}
    //     </span>
    //   ),
    // },
    {
      key: "actions",
      render: (_: any, record: any) =>
        record?.status == "pending" ? (
          <div className="flex-center-content gap-2">
            <button
              onClick={() => ChangeStatus("reject", record?.id)}
              className="app-btn outline-btn !py-2.5 !px-5 !min-h-fit !text-sm !min-w-10"
            >
              {t("tables.reject")}
            </button>
            <button
              onClick={() => ChangeStatus("accept", record?.id)}
              className="app-btn !py-2.5 !px-5 !min-h-fit !text-sm !min-w-10"
            >
              {t("tables.accept")}
            </button>
          </div>
        ) : (
            record?.status == "accept"? (
              <span className="flex-center-content w-fit mx-auto gap-2 bg-success-500/20 text-xs px-2 py-1.5 text-success-600 font-semibold rounded-lg">
                  <SuccessIcon className="size-5" /> {t("Text.accepted")}
              </span>
            ):(
              <span className="flex-center-content w-fit mx-auto gap-2 bg-error-100 text-xs px-2 py-1.5 text-error-300 font-semibold rounded-lg">
                  <FailedIcon /> {t("Text.rejected")}
              </span>
            ) 
        ),
      align: "center",
    },
  ];

  return (
    <>
      <AppTable
        columns={columns}
        dataSource={localItems}
        pagination={false}
        tableTitle={t("Text.products")}
        showSelection={false}
      />
      <AppModal
        modalTitle={t("tables.returnReason")}
        isModalVisible={openModal}
        onCancel={() => setOpenModal(false)}
      >
        <div className="flex items-center justify-center flex-col gap-5">
          {selectedItem?.reason_image && (
            <ImageWithFallback
              width={500}
              height={500}
              src={selectedItem?.reason_image || ""}
              alt={selectedItem?.reason}
              className="size-32"
            />
          )}
          <h5 className="text-lg text-center text-text-gray font-semibold">
            {selectedItem?.reason}
          </h5>
        </div>
      </AppModal>
    </>
  );
};

export default ReturnProductsTable;
