"use client";

import { useState } from "react";
import { Dropdown, Radio, Button, Spin } from "antd";
import { ArrowUpIcon } from "@/assets/svgs/Icons";
import toast from "react-hot-toast";
import { showDynamicSwal } from "@/utils/helpers";
import { useTranslations } from "next-intl";
import axiosInstance from "@/services/axiosClient";
import Success from "@/assets/images/success2.gif";

interface Props {
  order:any;
  setTempStatus:any;
  tempStatus:string;
  type:"order" | "return"
}

const ChangeStatus = ({order,setTempStatus,tempStatus,type}:Props) => {
  console.log("🚀 ~ ChangeStatus ~ order:", order)
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const t = useTranslations();
  const statusOptions = type =="order" ? ["prepared","shipped", "completed"] : ["shipped","returned"];

  const handleConfirm = () => {
    setOpen(false);
  };

  const handleChangeStatus = async (orderNumber:string,status:string)=>{
    try{
      setLoading(true)
          const endpoint = type =="order" ? `/my-orders/${order?.order_number}/change-status` : `/my-returns/${order?.id}/track`;
          const {data} = await axiosInstance.patch(endpoint,{"status" : status })
          if(data){
              await showDynamicSwal({
              title: t("Text.change_status"),
              imageUrl: `${Success.src}`,
              text: "",
              confirmButtonText: t("NAV.home"),
              showCancelButton: false,
              showConfirmButton: false,
              timer: 1500,
              customClass: {
                title: "swal-title",
                text: "hidden",
              },
            });
            setTempStatus(status)
          }
    }catch(error:any){
      toast.error(error?.response?.data?.message);
    }finally{
      setLoading(false)
    }
  }

  const items = [
    {
      key: "status-options",
      label: (
        <div onClick={(e) => e.stopPropagation()}>
          <Radio.Group
            onChange={(e) => handleChangeStatus(order?.order_number, e.target.value)}
            value={tempStatus}
            className="flex flex-col gap-2 !w-full"
            >
            {statusOptions.map((status, index) => {
              const currentIndex = statusOptions.indexOf(tempStatus);
              const isDisabled = index !== currentIndex + 1;
              return (
                <Radio key={`status_${status}`} value={status} className="sort-checkbox" disabled={isDisabled}>
                  {t(`status.${status}`)}
                </Radio>
              );
            })}
          </Radio.Group>
        </div>
      ),
    },
    {
      key: "confirm",
      label: (
        <button onClick={handleConfirm} className="w-full text-end text-primary  font-bold mt-2 mb-4">
          {t("buttons.confirm")}
        </button>
      ),
    },
  ];

  return (
    <Dropdown
      menu={{ items }}
      placement="bottom"
      trigger={["click"]}
      rootClassName="change-status-btns"
    >
      <Spin spinning={loading}>
        <button className="flex items-center gap-8 font-semibold h-fit bg-secprimary text-primary p-4 rounded-full">
          {t(`status.${tempStatus}`)} <ArrowUpIcon className="*:stroke-primary rotate-180" />
        </button>
      </Spin>
    </Dropdown>
  );
};

export default ChangeStatus;
