import { Checkbox, Col, Divider, Input, Row } from "antd";
import { useEffect, useState } from "react";

import { ERcbTier } from "@devowl-wp/api-real-cookie-banner";
import { jsxJoin } from "@devowl-wp/react-utils";

import { TemplateCenterCards } from "./cards.js";
import { useI18n } from "../../contexts/i18n.js";
import { useTemplateCenter } from "../../contexts/templateCenter.js";
import { useUpsell } from "../../contexts/upsell.js";

import type { TemplateCenterAllowedTypes } from "../../contexts/templateCenter.js";
import type { ComponentProps, PropsWithChildren } from "react";

function TemplateCenterFilter<TemplateType extends TemplateCenterAllowedTypes>({
    children,
    cards,
    onFetched,
}: PropsWithChildren<{
    cards: ComponentProps<typeof TemplateCenterCards<TemplateType>>;
    onFetched: (templates: TemplateType["afterPersist"][]) => void;
}>) {
    const [busy, setBusy] = useState(false);
    const { __, _i } = useI18n();
    const { isPro, isLicensed } = useUpsell();
    const { fetchTemplates, enableLocalFilter } = useTemplateCenter();

    const [term, setTerm] = useState("");
    const [isShowOnlyFree, setShowOnlyFree] = useState(false);

    useEffect(() => {
        if (isLicensed) {
            setBusy(true);
            fetchTemplates({ term, isShowOnlyFree })
                .then((items) => {
                    let result = items;
                    if (enableLocalFilter) {
                        result = result
                            .filter(({ tier }) => (isPro ? true : isShowOnlyFree ? tier !== ERcbTier.Pro : true))
                            .filter(({ headline, subHeadline }) =>
                                term.trim().length
                                    ? term
                                          .split(" ")
                                          .filter(Boolean)
                                          .filter(
                                              (singleTerm) =>
                                                  // Include description in search index
                                                  `${headline} ${subHeadline || ""}`
                                                      .toLowerCase()
                                                      .indexOf(singleTerm.trim().toLowerCase()) > -1,
                                          ).length > 0
                                    : true,
                            );
                    }

                    onFetched(result);
                })
                .finally(() => {
                    setBusy(false);
                });
        }
    }, [onFetched, term, isShowOnlyFree, isLicensed]);

    return (
        <div style={{ marginBottom: 20 }}>
            {children}
            {isLicensed && (
                <Input.Search
                    autoFocus
                    loading={busy}
                    style={{ maxWidth: 400 }}
                    placeholder={__("Search template by name...")}
                    onChange={(e) => setTerm(e.target.value)}
                />
            )}
            <Row style={{ marginTop: 10 }} justify="center" align="middle" gutter={[10, 16]}>
                {jsxJoin(
                    [
                        !isPro && (
                            <Col key="isShowOnlyFree">
                                <Checkbox
                                    key="isShowOnlyFree"
                                    onChange={() => setShowOnlyFree(!isShowOnlyFree)}
                                    disabled={!isLicensed}
                                    style={{ marginRight: -8 }}
                                >
                                    {__("Show only free templates")}
                                </Checkbox>
                            </Col>
                        ),
                    ].filter(Boolean),
                    <Col>
                        <Divider type="vertical" />
                    </Col>,
                )}
            </Row>
            {term.length > 0 && cards.templates.length === 0 ? (
                <div
                    className="notice notice-warning inline below-h2 notice-alt"
                    style={{ margin: "10px 0 0 0", maxWidth: 400, display: "inline-block" }}
                >
                    <p>
                        {_i(
                            __(
                                "{{strong}}No template found{{/strong}}. Please try to create the service yourself or {{a}}contact us{{/a}} and let us know for which service you need a template.",
                            ),
                            {
                                strong: <strong />,
                                a: <a href={__("https://devowl.io/support/")} target="_blank" rel="noreferrer" />,
                            },
                        )}
                    </p>
                </div>
            ) : (
                isLicensed && <TemplateCenterCards<TemplateType> {...cards} />
            )}
        </div>
    );
}

export { TemplateCenterFilter };
