"use client";
import React, { useEffect, useState } from "react";
import AppTable from "@/components/UiComponents/table/AppTable";
import { Tag } from "antd";
import { ViewIcon } from "@/assets/svgs/TraderIcons";
import ImageWithFallback from "@/components/UiComponents/ImageWithFallback";
import LocalePath from "@/components/UiComponents/LocalePath";
import { useTranslations } from "next-intl";
import { useRouter, useSearchParams } from "next/navigation";
import { getMyReturns } from "@/services/ClientApiHandler";
import RenderPaymentInfo from "@/components/sharedComponents/cards/RenderPayment";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";

const ReturnsTable = () => {
  const t = useTranslations();

  const searchParams = useSearchParams();
  const router = useRouter();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const { refetch } = useSelector((state: RootState) => state.socketConfig);

  const fetchData = async () => {
    try{
      setLoading(true);
      const params = new URLSearchParams(searchParams.toString());
      const response = await getMyReturns(params);
      if(response){
        setData(response);
      }
    }catch(error:any){
      console.log("🚀 ~ fetchData ~ error:", error)
      // toast.error(error.response?.data?.message )
    }finally{
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [searchParams.toString()]);

  const handlePageChange = (page: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("page", page.toString());
    router.push(`?${params.toString()}`);
  };

  useEffect(() => {
    if (refetch?.type === "return") {
      fetchData();
    }
  }, [refetch]);


  const columns = [
    {
      title: t("tables.orderNumber"),
      dataIndex: "order_number",
      key: "order_number",
    },
    {
      title: t("tables.clientName"),
      dataIndex: "client",
      key: "client",
    },
    {
      title: t("tables.products"),
      dataIndex: "products",
      key: "products",
      render: (_:any,record:any) => (
        <div className="flex items-center min-w-[6rem]">
          {record?.media?.slice(0,3)?.map((el:any, index:number) => (
              <ImageWithFallback
                key={`products_image_${index}`}
                src={el}
                width={80}
                height={80}
                alt={`product-name`}
                className="size-12 object-contain -me-6 bg-greynormal rounded-2xl border border-platinum"
              />
            ))}
        </div>
      ),
      width: 40,
    },
    {
      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.orderStatus"),
      dataIndex: "return_status",
      key: "return_status",
      render: (status: any) => (
        <Tag
          color={
            status === "pending"
              ? "gray"
              : status == "prepared"
              ? "purple"
              : status === "cancelled"
              ? "red"
              : status === "shipped"
              ? "gold":"green"
          }
        >
          {t(`status.${status}`)}
        </Tag>
      ),
    },
    {
      title: t("tables.paymentMethod"),
      dataIndex: "payment_method",
      key: "payment_method",
      render: (method: string) => <RenderPaymentInfo payment_method={method} />,
    },
    {
      title: t("tables.orderDate"),
      dataIndex: "created_at",
      key: "created_at",
    },
    {
      title: t("tables.action"),
      key: "action",
      render: (_: any, record: any) => (
        <LocalePath
          href={`/returns/${record?.id}`}
          className="border inline-flex items-center justify-center border-platinum rounded-xl p-2"
        >
          <ViewIcon className="size-6" />
        </LocalePath>
      ),
      align: "center",
    },
  ];
  
  const filterStatuses = [
    {id:"pending",name:t("order_statuses.pending")},
    {id:"shipped",name:t("order_statuses.shipped")},
    {id:"returned",name:t("order_statuses.returned")}
  ]


  return (
    <AppTable
        loading={loading}
        columns={columns}
        dataSource={data?.data}
        pagination={{
          pageSize: data?.meta?.per_page,
          total: data?.meta?.total,
          current: data?.meta?.current_page,
          onChange: handlePageChange,
        }}
        showSelection={false}
        hasFilter
        filterProps={{
          statusData:filterStatuses,
          dateTitle:"tables.returnDate",
          statusTitle:"LABELS.status"
        }}
        hasSearch
    />
  );
};

export default ReturnsTable;