var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { SkeletonCard } from "./SkeletonCard";
import { useUser } from "@web/user/UserProvider";
import { useNavigate, useParams } from "react-router-dom";
import { TemplateCard } from "./TemplateCard";
import ErrorPage from "@web/ErrorPage";
import { Button } from "@/components/ui/button";
import Paginator from "./Paginator";
import { Plus } from "lucide-react";
import Searcher from "./Searcher";
const TemplateBrowser = ({ mine }) => {
    const { search = "", language = "all", page = "1", publishedId = null, } = useParams();
    const [templates, setTemplates] = useState(null);
    const [drafts, setDrafts] = useState(null);
    const [showDrafts, setShowDrafts] = useState(false);
    const [networkError, setNetworkError] = useState(false);
    const [selectedLang, setSelectedLang] = useState(language);
    const [newSearch, setNewSearch] = useState(search);
    const navigate = useNavigate();
    const showSearch = publishedId === null && mine !== true;
    const { user } = useUser();
    let pg = 1;
    pg = Number.parseInt(page);
    useEffect(() => {
        if (publishedId === null && !mine) {
            getTemplates(setTemplates, setNetworkError, pg, language, search);
        }
        else if (!mine) {
            getVariants(setTemplates, setNetworkError, Number.parseInt(publishedId), pg);
        }
        else {
            if (user === null) {
                navigate("/signin");
            }
            else {
                getMine(setTemplates, setDrafts, setNetworkError, user, pg);
            }
        }
    }, [search, language, page]);
    if (networkError) {
        return (_jsx(ErrorPage, { title: "Network Error", description: "Try refresh the page" }));
    }
    const skeletons = Array(30)
        .fill(null)
        .map((_, index) => _jsx(SkeletonCard, {}, index));
    let cards;
    if (templates === null) {
        cards = skeletons;
    }
    else if (templates.length === 0) {
        return (_jsx(ErrorPage, { title: "No templates match your search.", description: "Try using a less specific search, navigate to a previous page, or create a template.", children: _jsx("div", { className: "flex justify-center p-10", children: _jsx(Button, { onClick: () => navigate("/browse"), variant: "outline", type: "submit", children: "Reset" }) }) }));
    }
    else if (showDrafts) {
        cards = drafts.map((template, index) => (_jsx("div", { children: _jsx(TemplateCard, { template: { template, creator: user } }) }, index)));
    }
    else {
        cards = templates.map((template, index) => (_jsx("div", { children: _jsx(TemplateCard, { template: template }) }, index)));
    }
    return (_jsxs("div", { className: "h-full max-h-full", children: [mine ? (_jsxs("div", { className: "flex justify-center gap-5", children: [_jsx(Button, { onClick: () => setShowDrafts(true), variant: showDrafts ? "default" : "outline", children: "Drafts" }), _jsx(Button, { onClick: () => setShowDrafts(false), variant: !showDrafts ? "default" : "outline", children: "Published" })] })) : (_jsx(_Fragment, {})), showSearch ? (_jsx(Searcher, { newSearch: newSearch, setNewSearch: setNewSearch, selectedLang: selectedLang, setSelectedLang: setSelectedLang })) : (_jsx(_Fragment, {})), _jsx("div", { className: "flex h-full max-h-full justify-center overflow-scroll sm:p-10", children: _jsxs("div", { className: "flex h-full max-h-full flex-wrap justify-center gap-5", children: [cards, _jsx("div", { className: "w-full p-24" })] }) }), _jsx("div", { className: "fixed bottom-0 flex w-full justify-center bg-background py-5", children: _jsx(Paginator, { search: search, language: language, pg: pg }) }), _jsx("a", { href: "/create", children: _jsx(Button, { size: "icon", className: "center fixed bottom-16 right-1/2 rounded sm:bottom-14 sm:right-14", children: _jsx(Plus, {}) }) })] }));
};
const getTemplates = (setTemplates, setNetworkError, page, language, search) => __awaiter(void 0, void 0, void 0, function* () {
    const apiPath = "/api/browse";
    const toSubmit = {
        page: page,
        language: language,
        search: search,
    };
    const request = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(toSubmit),
    };
    try {
        const response = yield fetch(apiPath, request);
        const json = yield response.json();
        if (response.ok) {
            setTemplates(json);
        }
        else {
            setNetworkError(true);
        }
    }
    catch (error) {
        console.log(error);
    }
});
const getVariants = (setTemplates, setNetworkError, publishedId, page) => __awaiter(void 0, void 0, void 0, function* () {
    const apiPath = "/api/variants";
    const toSubmit = {
        page: page,
        publishedId: publishedId,
    };
    const request = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(toSubmit),
    };
    try {
        const response = yield fetch(apiPath, request);
        const json = yield response.json();
        if (response.ok) {
            setTemplates(json);
        }
        else {
            setNetworkError(true);
        }
    }
    catch (error) {
        console.log(error);
    }
});
const getMine = (setTemplates, setDrafts, setNetworkError, username, page) => __awaiter(void 0, void 0, void 0, function* () {
    const apiPath = "/api/mine";
    const toSubmit = {
        page: page,
        username: username,
    };
    const request = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(toSubmit),
    };
    try {
        const response = yield fetch(apiPath, request);
        const json = yield response.json();
        if (response.ok) {
            const { drafts, published } = json;
            setTemplates(published);
            setDrafts(drafts);
        }
        else {
            setNetworkError(true);
        }
    }
    catch (error) {
        console.log(error);
    }
});
export default TemplateBrowser;
