/* eslint-disable @typescript-eslint/no-unused-vars */
import { LoadingOverlay, Modal, ModalProps } from "@mantine/core";
import { useCallback, useEffect, useMemo, useState } from "react";
import { getDetailBidHistories } from "../../../apis/bid-histories";
import { IBid } from "../../../system/type";
import GraysHistoriesView from "./grays-histories-view";
import constants from "../../../constant";
import PicklesHistoriesView from "./pickles-histories-view";
import AllbidsHistoriesView from "./allbids-histories-view";

export interface IShowHistoriesApiModalProps extends ModalProps {
  data: IBid | null;
  onUpdated?: () => void;
}

export default function ShowHistoriesApiModal({
  data,
  onUpdated,
  ...props
}: IShowHistoriesApiModalProps) {
  const [histories, setHistories] = useState<Record<string, string>[]>([]);

  const [loading, setLoading] = useState(false);

  const handleCallApi = useCallback(async () => {
    if (!data?.lot_id) {
      setHistories([]);

      return;
    }

    setLoading(true);
    const response = await getDetailBidHistories(data?.lot_id);
    setLoading(false);

    if (response.data && response.data) {
      const values = (response.data as Record<string, string>[]).map(
        (item, index) => {
          return {
            ...item,
            row_id: String(index),
          };
        }
      );

      setHistories(values);
    }
  }, [data]);

  useEffect(() => {
    handleCallApi();
  }, [handleCallApi]);

  const generateView = useMemo(() => {
    switch (data?.web_bid.origin_url) {
      case constants.grays:
        return <GraysHistoriesView histories={histories} />;
      case constants.pickles:
        return <PicklesHistoriesView histories={histories} />;
      case constants.allbids:
        return <AllbidsHistoriesView histories={histories} />;
    }
  }, [data?.web_bid.origin_url, histories]);

  return (
    <Modal
      className="relative"
      {...props}
      size="xl"
      title={<span className="text-xl font-bold">BIDDING HISTORY</span>}
      centered
    >
      {generateView}
      <LoadingOverlay
        visible={loading}
        zIndex={1000}
        overlayProps={{ blur: 2 }}
      />
    </Modal>
  );
}
