import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts/highstock";
// @ts-ignore
import color from "color";
import BigNumber from "bignumber.js";
import React from "react";
import { t } from "ttag";
import { Box } from "../grid";
import Space from "../space";
import Text from "../text";
import { safeToFixed } from "../../utils/format";
import Actions from "./actions";
import BackBtn from "./back";
import { Period } from "./types";
import { coinToIcon } from "./util";
import { currentTheme } from "../../theme";
const periodLabel = {
    [Period.Year]: "1Y",
    [Period.Quarter]: "3M",
    [Period.Month]: "1M",
    [Period.Week]: "1W",
    [Period.Day]: "1D",
};
const withSign = (num) => num > 0 ? `+$${num.toFixed(2)}` : `-$${Math.abs(num).toFixed(2)}`;
const transferType = (transfer, account) => {
    switch (transfer.transferReason1) {
        case "Common":
        case "Subaccount":
            if (transfer.accountId1 === account.address) {
                return t `Sent`;
            }
            else {
                return t `Received`;
            }
        case "TreasuryEqBuyout":
            return t `Buy EQ`;
        default:
            return "Unknown"; // TODO
    }
};
const History = ({ account, bailsman, borrower, lender, currency, stableCurrency, onClose, rateHistory, getRateHistory, transferHistory, period, setPeriod, onEntryClick, onSwitch, network, convert, balance, firstBlockAt, block, chainId, }) => {
    const [rawHistory, setHistory] = React.useState();
    const transformedHistory = React.useMemo(() => {
        const entries = rawHistory?.points ?? rateHistory?.points ?? [];
        const history = [];
        const width = Math.min(200, entries.length);
        const k = entries.length < 200 ? 1 : entries.length / 200;
        let min = Infinity;
        let max = -Infinity;
        for (let i = 0; i < width; ++i) {
            const { timestamp, price: rawPrice } = entries[Math.floor(i * k)];
            const price = Number(rawPrice);
            if (price < min) {
                min = price;
            }
            if (price > max) {
                max = price;
            }
            history.push({
                timestamp,
                price,
            });
        }
        return {
            min,
            max,
            data: history.reverse(),
        };
    }, 
    /*
      ...(rawHistory ?? []),
      convert(new BigNumber(1), currency, "Usd").toNumber(),
    */
    [rawHistory, rateHistory, currency]);
    const history = React.useMemo(() => {
        if (!block || !firstBlockAt) {
            return transformedHistory;
        }
        const { min, max, data } = transformedHistory;
        const price = convert(new BigNumber(1), currency, "Usd").toNumber();
        const timestamp = Date.now();
        return {
            min: Math.min(price, min),
            max: Math.max(price, max),
            data: [...data, ...[{ timestamp, price }]],
        };
    }, [transformedHistory, currency, block, convert, firstBlockAt]);
    const formatAddress = React.useCallback((address) => {
        if (address === bailsman?.address) {
            return t `Bailout pool`;
        }
        else if (address === borrower?.address) {
            return t `Collateral pool`;
        }
        else if (address === lender?.address) {
            return t `Lending pool`;
        }
        else {
            return address.slice(0, 4) + ".." + address.slice(-4);
        }
    }, [bailsman, borrower, lender]);
    const close = React.useCallback(() => {
        onClose();
    }, [onClose]);
    const getIntervalForRateHistory = (period) => {
        const HOUR = 3_600; // in seconds
        const FOUR_HOURS = 4 * HOUR;
        const ONE_DAY = 24 * HOUR;
        const MAX_COUNT_OF_POINTS = 200;
        if (period / HOUR <= MAX_COUNT_OF_POINTS) {
            return ["h", period / HOUR];
        }
        else if (period / FOUR_HOURS <= MAX_COUNT_OF_POINTS) {
            return ["4h", period / FOUR_HOURS];
        }
        else if (period / ONE_DAY <= MAX_COUNT_OF_POINTS) {
            return ["d", period / ONE_DAY];
        }
        return ["d", MAX_COUNT_OF_POINTS];
    };
    React.useEffect(() => {
        (async () => {
            const [timeframe, points] = getIntervalForRateHistory(period);
            const res = await getRateHistory?.(undefined, {
                points: points.toString(),
                token: currency,
                chainId,
                timeframe,
            });
            if (!chainId)
                return;
            setHistory(res);
        })();
    }, [currency, chainId, period]);
    const options = React.useMemo(() => {
        if (history && firstBlockAt) {
            const x = history.data.map(({ timestamp }) => {
                const date = new Date(timestamp);
                return date.toLocaleString();
            });
            const primaryColor = color(currentTheme.colors.primary);
            const options = {
                chart: {
                    type: "area",
                    height: 140,
                    width: 265,
                },
                title: {
                    text: "",
                },
                legend: {
                    enabled: false,
                },
                credits: {
                    enabled: false,
                },
                yAxis: {
                    min: history.min,
                    max: history.max,
                    opposite: false,
                    lineWidth: 0,
                    offset: 0,
                    gridLineWidth: 0,
                    title: {
                        text: "",
                    },
                    tickWidth: 0,
                    tickLength: 0,
                    tickPosition: undefined,
                    labels: {
                        enabled: false,
                    },
                },
                xAxis: {
                    categories: x,
                    tickmarkPlacement: "on",
                    lineWidth: 0,
                    labels: {
                        style: {
                            fontSize: "4px",
                            visibility: "hidden",
                        },
                    },
                },
                tooltip: {
                    split: true,
                    valueSuffix: "",
                },
                plotOptions: {
                    series: {
                        color: primaryColor.hex(),
                    },
                    area: {
                        stacking: "normal",
                        lineColor: primaryColor.hex(),
                        lineWidth: 1,
                        marker: {
                            lineWidth: 1,
                            lineColor: primaryColor.hex(),
                            enabled: false,
                        },
                        fillColor: {
                            linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                            stops: [
                                [0, primaryColor.alpha(0.22).toString()],
                                [0.3, primaryColor.alpha(0.16).toString()],
                                [0.5, primaryColor.alpha(0.08).toString()],
                                [0.7, primaryColor.alpha(0.05).toString()],
                                [1, "rgb(196, 196, 196, 0.03)"],
                            ],
                        },
                    },
                },
                series: [
                    { name: "price", data: history.data.map(({ price }) => price) },
                ],
            };
            return options;
        }
    }, [history, period, firstBlockAt]);
    const entries = transferHistory.filter(({ currency1: token }) => currency === token);
    return (_jsxs(_Fragment, { children: [_jsx(BackBtn, { onClose: close }), _jsx(Box, { pl: "16px", pt: "16px", children: _jsx(Text.F2, { children: t `Wallet balance` }) }), _jsxs("div", { className: "wallet__balance", children: [_jsx(Text.F2, { className: "name", children: currency.toUpperCase() }), balance && (_jsxs(_Fragment, { children: [_jsx(Text.F2, { className: "amount", children: safeToFixed(balance[currency], 4, true) ?? "0" }), network?.dev && (_jsxs(Text.F2, { className: "value", children: [safeToFixed(convert(balance[currency], currency, "Usd"), 4, true), "$"] }))] }))] }), _jsx(Actions, { onSwitch: onSwitch, network: network }), _jsx(Space, { height: 11, style: {
                    borderBottom: `1px solid ${currentTheme.colors.border}`,
                } }), _jsxs("div", { className: "row token-icon", children: [coinToIcon[currency], _jsxs("div", { className: "group", children: [_jsx(Text.T4, { fontFamily: "Bold", children: currency.toUpperCase() }), _jsx(Text.F2, { children: currency /* TODO full name */ })] }), history && (_jsxs("div", { className: "group", style: { marginLeft: "auto" }, children: [_jsxs(Text.T4, { fontFamily: "Bold", children: ["$", history.data.slice(-1)?.[0]?.price.toFixed(2)] }), currency !== "Usd" && (_jsx(Text.F2, { children: withSign((history.data.slice(-1)?.[0]?.price ?? 0) -
                                    (history.data[0]?.price ?? 0)) }))] }))] }), history && currency !== "Usd" && currency !== stableCurrency && (_jsxs(_Fragment, { children: [_jsx("div", { className: "row chart", children: _jsx(HighchartsReact, { highcharts: Highcharts, options: options }) }), _jsx("div", { className: "row", style: {
                            justifyContent: "center",
                            borderBottom: `1px solid ${currentTheme.colors.border}`,
                        }, children: Object.entries(periodLabel).map(([val, title]) => (_jsx(Text.F2, { style: {
                                background: val === period
                                    ? currentTheme.colors.primary
                                    : "transparent",
                                cursor: "pointer",
                                marginRight: 10,
                                padding: "2px 8px",
                                borderRadius: 4,
                                color: val === period ? "white" : currentTheme.colors.primary,
                            }, onClick: () => setPeriod(val), children: title }, val))) })] })), _jsx(Space, { height: 16 }), entries.length > 0 && (_jsx(Box, { pl: "16px", pt: "16px", pb: "3px", children: _jsx(Text.F2, { children: t `History` }) })), _jsx("div", { className: "transfers", children: entries.map((entry) => (_jsxs("div", { className: "row transfer", onClick: () => onEntryClick?.(entry), children: [_jsxs(Box, { children: [_jsx(Text.F1, { children: transferType(entry, account) }), _jsxs(Text.F4, { gray: true, children: [t `block`, ":\u00A0", entry.blockNumber /* TODO link to blockexplorer */] })] }), _jsxs(Box, { children: [_jsxs(Text.F1, { textAlign: "right", children: [safeToFixed(new BigNumber(entry.balance1 ?? "0", 10), 4, true), "\u00A0", currency] }), _jsxs(Text.F4, { gray: true, textAlign: "right", children: [t `from`, ":\u00A0", entry.accountId1 ? formatAddress(entry.accountId1) : "", "\u00A0\u00A0", t `to`, ":\u00A0", entry.accountId2 ? formatAddress(entry.accountId2) : ""] })] })] }, entry.blockNumber))) })] }));
};
export default History;
//# sourceMappingURL=history.js.map