"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MyCardsView = MyCardsView;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const ink_1 = require("ink");
const TrelloContext_1 = require("../state/TrelloContext");
const NavigationContext_1 = require("../state/NavigationContext");
const ink_spinner_1 = tslib_1.__importDefault(require("ink-spinner"));
function MyCardsView() {
    const { loadAssignedCards, state: trelloState, cache } = (0, TrelloContext_1.useTrello)();
    const { dispatch, config } = (0, NavigationContext_1.useNavigation)();
    const [cards, setCards] = (0, react_1.useState)([]);
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [error, setError] = (0, react_1.useState)(null);
    const [selectedIndex, setSelectedIndex] = (0, react_1.useState)(0);
    const [boardNames, setBoardNames] = (0, react_1.useState)({});
    const [listNames, setListNames] = (0, react_1.useState)({});
    (0, react_1.useEffect)(() => {
        setLoading(true);
        loadAssignedCards()
            .then(async (result) => {
            setCards(result);
            // Resolve board and list names from cache
            const boards = {};
            const lists = {};
            for (const card of result) {
                if (!boards[card.idBoard]) {
                    try {
                        boards[card.idBoard] = await cache.getBoard(card.idBoard);
                    }
                    catch {
                        boards[card.idBoard] = card.idBoard;
                    }
                }
                if (!lists[card.idList]) {
                    try {
                        lists[card.idList] = await cache.getList(card.idList);
                    }
                    catch {
                        lists[card.idList] = card.idList;
                    }
                }
            }
            setBoardNames(boards);
            setListNames(lists);
        })
            .catch((e) => setError(e.message))
            .finally(() => setLoading(false));
    }, [loadAssignedCards, cache]);
    // Group cards by due date status
    const groups = react_1.default.useMemo(() => {
        const overdue = [];
        const today = [];
        const thisWeek = [];
        const later = [];
        const noDue = [];
        const now = new Date();
        for (const card of cards) {
            if (!card.due) {
                noDue.push(card);
                continue;
            }
            const dueDate = new Date(card.due);
            const diffDays = Math.ceil((dueDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
            if (diffDays < 0)
                overdue.push(card);
            else if (diffDays === 0)
                today.push(card);
            else if (diffDays <= 7)
                thisWeek.push(card);
            else
                later.push(card);
        }
        const result = [];
        if (overdue.length)
            result.push({ title: `Overdue (${overdue.length})`, color: "red", cards: overdue });
        if (today.length)
            result.push({ title: `Due Today (${today.length})`, color: "yellow", cards: today });
        if (thisWeek.length)
            result.push({
                title: `Due This Week (${thisWeek.length})`,
                color: "green",
                cards: thisWeek,
            });
        if (later.length)
            result.push({ title: `Later (${later.length})`, color: "blue", cards: later });
        if (noDue.length)
            result.push({
                title: `No Due Date (${noDue.length})`,
                color: "gray",
                cards: noDue,
            });
        return result;
    }, [cards]);
    // Flatten for navigation
    const allItems = react_1.default.useMemo(() => {
        const items = [];
        for (const group of groups) {
            items.push({ type: "header", group });
            for (const card of group.cards) {
                items.push({ type: "card", card, group });
            }
        }
        return items;
    }, [groups]);
    (0, ink_1.useInput)((input, key) => {
        var _a, _b;
        if (key.escape) {
            dispatch({ type: "SET_VIEW", view: "home" });
            return;
        }
        if (key.upArrow) {
            let newIndex = selectedIndex - 1;
            // Skip headers
            while (newIndex >= 0 && ((_a = allItems[newIndex]) === null || _a === void 0 ? void 0 : _a.type) === "header") {
                newIndex--;
            }
            if (newIndex >= 0)
                setSelectedIndex(newIndex);
            return;
        }
        if (key.downArrow) {
            let newIndex = selectedIndex + 1;
            // Skip headers
            while (newIndex < allItems.length &&
                ((_b = allItems[newIndex]) === null || _b === void 0 ? void 0 : _b.type) === "header") {
                newIndex++;
            }
            if (newIndex < allItems.length)
                setSelectedIndex(newIndex);
            return;
        }
    });
    if (loading) {
        return ((0, jsx_runtime_1.jsx)(ink_1.Box, { paddingX: 2, paddingY: 1, children: (0, jsx_runtime_1.jsxs)(ink_1.Text, { children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, children: (0, jsx_runtime_1.jsx)(ink_spinner_1.default, { type: "dots" }) }), " ", "Loading your assigned cards..."] }) }));
    }
    if (error) {
        return ((0, jsx_runtime_1.jsx)(ink_1.Box, { paddingX: 2, paddingY: 1, children: (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: config.theme.error, children: ["Error: ", error] }) }));
    }
    if (cards.length === 0) {
        return ((0, jsx_runtime_1.jsx)(ink_1.Box, { paddingX: 2, paddingY: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: "No cards assigned to you. Press [Esc] to go back." }) }));
    }
    return ((0, jsx_runtime_1.jsx)(ink_1.Box, { flexDirection: "column", paddingX: 1, children: allItems.map((item, index) => {
            if (item.type === "header" && item.group) {
                return ((0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: index > 0 ? 1 : 0, paddingX: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, color: item.group.color, children: item.group.title }) }, `header-${item.group.title}`));
            }
            if (item.type === "card" && item.card) {
                const isSelected = index === selectedIndex;
                const card = item.card;
                const boardName = boardNames[card.idBoard] || "";
                const listName = listNames[card.idList] || "";
                return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { paddingX: 1, children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { color: isSelected ? config.theme.primary : undefined, bold: isSelected, children: [isSelected ? "> " : "  ", card.name] }), (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: config.theme.muted, children: [" ", boardName, " / ", listName] })] }, card.id));
            }
            return null;
        }) }));
}
