import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";

import { ListIcon } from "@components/common/Icons";
import { ModalCloseBtn } from "@components/common/ModalHeader";
import { SlideInPanel } from "@components/common/SlideInPanel";
import {
	type OrderData,
	useAutoHistory,
} from "@hooks/apis/auto/useAutoHistory";
import { useManualHistory } from "@hooks/apis/manual/useManualHistory";
import { useAccounts } from "@hooks/useAccounts";
import {
	ScreenTab,
	setScreenTab,
	toggleHistoryModal,
} from "@store/globalSlice";
import { setInflightData } from "@store/inflightSlice";
import type { ReduxStateType } from "@store/types";
import { EmptyHistory } from "./EmptyHistory";
import { HistoryTabsHeader, type Tab } from "./Header";
import { HistoryItem } from "./HistoryItem";

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

	// Needs at least one wallet connected!
	if (!account?.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"
		>
			<ListIcon />
		</button>
	);
};

export const HistoryModal = () => {
	const dispatch = useDispatch();
	const { accounts } = useAccounts();
	const showHistoryModal = useSelector(
		(state: ReduxStateType) => state.global.showHistoryModal,
	);
	const [tab, setTab] = useState<"auto" | "manual">("auto");
	const [pageNumber, setPageNumber] = useState<number>(1);
	const pageSize = 5;

	function closePanel() {
		dispatch(toggleHistoryModal(false));
	}

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

	const {
		data: autoPaginatedData,
		totalPages: totalAutoPages,
		refetch: refetchAutoHistory,
		isSuccess: isAutoFetched,
		isLoading: isAutoLoading,
	} = useAutoHistory({
		userAddresses: accounts
			.filter(
				(account) => account.address !== undefined && account.chainType === "EVM", // Only EVM accounts have auto swap history
			)
			.map((account) => account.address),
		pageSize,
		pageNumber,
	});

	const {
		paginatedData: manualPaginatedData,
		totalPages: totalManualPages,
		dataAvailable: manualDataAvailable,
	} = useManualHistory({
		userAddresses: accounts
			.map((account) => account.address)
			.filter((address) => address !== undefined),
		pageNumber,
		pageSize,
	});

	const data = tab === "auto" ? autoPaginatedData : manualPaginatedData;

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

	// sets page to 1 on tab change
	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		setPageNumber(1);
	}, [tab]);

	const autoDataAvailable = useMemo(
		() => autoPaginatedData?.length > 0 || pageNumber > 1,
		[autoPaginatedData, pageNumber],
	);

	const noHistory = !autoDataAvailable && !manualDataAvailable;

	const tabList: Tab[] = [
		{
			id: "auto",
			onClick: () => setTab("auto"),
			isActive: tab === "auto",
			enabled: autoDataAvailable,
		},
		{
			id: "manual",
			onClick: () => setTab("manual"),
			isActive: tab === "manual",
			enabled: Boolean(manualDataAvailable),
		},
	];

	/**
	 * Hook to select auto when available
	 * Else selects manual
	 */

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (isAutoFetched) {
			if (autoDataAvailable && tab !== "manual") setTab("auto");
			else if (manualDataAvailable) setTab("manual");
		}
	}, [autoDataAvailable, manualDataAvailable, isAutoFetched]);

	return (
		<SlideInPanel
			closePanel={closePanel}
			isVisible={showHistoryModal}
			cardClasses="bn-flex bn-flex-col bn-h-full bn-overflow-hidden"
			trayClasses="bn-border-none"
		>
			<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 />
			) : (
				<div className="bn-flex-1 bn-overflow-hidden bn-flex bn-flex-col">
					<HistoryTabsHeader
						tabs={tabList}
						setPage={(value: number) => setPageNumber(value)}
						pageNumber={pageNumber}
						totalPages={tab === "auto" ? totalAutoPages : (totalManualPages ?? 0)}
					/>
					<div className="bn-flex-1 bn-overflow-auto bn-px-4 bn-pb-4 bn-space-y-2">
						{isAutoLoading && tab === "auto" ? (
							<span className="bn-text-secondary">Loading...</span>
						) : (
							data?.map((item) => (
								<HistoryItem
									data={item}
									key={item.requestHash}
									onClick={() => openInflight(item)}
								/>
							))
						)}
					</div>
				</div>
			)}
		</SlideInPanel>
	);
};
