"use client";

import Modal from "@/components/elements/Modal";
import BuyerOrderItem from "@/components/shops/orders/BuyerOrderItem";
import useAxios from "@/hooks/useAxios";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type BuyerOrder = any;

type ShopMyOrdersModalProps = {
  open: boolean;
  onClose: () => void;
  shopId: string;
};

export default function ShopMyOrdersModal({ open, onClose, shopId }: ShopMyOrdersModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [orders, setOrders] = useState<BuyerOrder[] | null>(null);

  useEffect(() => {
    if (!open) return;
    setOrders(null);
    request<{ docs: BuyerOrder[] }>("GET", `/orders?role=buyer&shopId=${shopId}`)
      .then((res) => setOrders(res?.docs || []))
      .catch(() => setOrders([]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, shopId]);

  return (
    <Modal
      isOpen={open}
      onClose={onClose}
      elevated
      height="fit"
      panelClassName="!p-0 max-h-[80dvh] w-full max-w-sm overflow-y-auto"
    >
      <div className="px-4 py-5">
        <h2 className="mb-4 text-center text-base font-bold">
          {t("shops.myOrdersFromShop")}
        </h2>
        {orders === null ? (
          <p className="py-8 text-center text-sm text-neutral-500">{t("common.loading")}</p>
        ) : orders.length === 0 ? (
          <p className="py-8 text-center text-sm text-neutral-500">
            {t("shops.noOrdersFromShop")}
          </p>
        ) : (
          orders.map((order) => <BuyerOrderItem key={order._id} order={order} />)
        )}
      </div>
    </Modal>
  );
}
