import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useAccount } from "wagmi";

import { MIcon } from "@components/common/MIcon";
import { ModalCloseBtn } from "@components/common/ModalHeader";
import { SlideInPanel } from "@components/common/SlideInPanel";
import { useOrderHistory } from "@hooks/apis/useOrderHistory";
import type { RequestStatus } from "@hooks/apis/useRequestStatus";
import {
	ScreenTab,
	setScreenTab,
	toggleHistoryModal,
} from "@store/globalSlice";
import { setInflightData } from "@store/inflightSlice";
import type { ReduxStateType } from "@store/types";
import { EmptyHistory } from "./EmptyHistory";
import { HistoryItem } from "./HistoryItem";
import { Stats } from "./Stats";

export const History = () => {
	const dispatch = useDispatch();
	const { isConnected } = useAccount();
	function openModal() {
		dispatch(toggleHistoryModal(true));
	}

	if (!isConnected) return null;

	return (
		<button
			className="bn-bg-transparent bn-h-9 bn-w-9 bn-flex bn-items-center bn-justify-center bn-border-none bn-cursor-pointer bn-text-primary"
			onClick={openModal}
			type="button"
		>
			<MIcon name="receipt_long" />
		</button>
	);
};

export const HistoryModal = () => {
	const dispatch = useDispatch();
	const { address } = useAccount();
	const showHistoryModal = useSelector(
		(state: ReduxStateType) => state.global.showHistoryModal,
	);
	function closePanel() {
		dispatch(toggleHistoryModal(false));
	}

	function openInflight(data: RequestStatus) {
		dispatch(
			setInflightData({
				requestHash: data.requestHash,
				data: data,
				requestType: data.requestType,
			}),
		);
		closePanel();
		dispatch(setScreenTab(ScreenTab.INFLIGHT));
	}

	// biome-ignore format:
	const {data, refetch} = useOrderHistory({userAddress: address as `0x${string}`})

	useEffect(() => {
		if (showHistoryModal) refetch();
	}, [showHistoryModal, refetch]);

	const noHistory = !data?.length;

	return (
		<SlideInPanel
			closePanel={closePanel}
			isVisible={showHistoryModal}
			cardClasses="bn-flex bn-flex-col bn-h-full"
		>
			<div className="bn-flex bn-items-center bn-justify-between bn-relative bn-p-4 bn-w-full">
				<p className="bn-text-primary bn-text-xl bn-font-semibold">Swap History</p>

				<ModalCloseBtn
					closeModal={closePanel}
					classNames="bn-bg-layer-2 bn-rounded-full bn-size-10"
				/>
			</div>

			{noHistory ? (
				<EmptyHistory />
			) : (
				<HistoryData data={data} openTransaction={openInflight} />
			)}
		</SlideInPanel>
	);
};

const HistoryData = ({
	data,
	openTransaction,
}: {
	data: RequestStatus[];
	openTransaction: (data: RequestStatus) => void;
}) => {
	return (
		<>
			{/* <div className="bn-px-4">
				<Stats />
			</div> */}

			<div className="bn-flex-1 bn-overflow-auto bn-p-4 bn-space-y-2">
				{data?.map((item) => (
					<HistoryItem
						data={item}
						key={item.requestHash}
						onClick={() => openTransaction(item)}
					/>
				))}
			</div>
		</>
	);
};
