import { Card, Col, Row, Spin } from "antd";
import { observer } from "mobx-react";
import { useEffect, useMemo, useState } from "react";

import { UpsellModal } from "@devowl-wp/react-cookie-banner-admin";

import { DashboardCacheCardContent } from "./cache.js";
import { DashboardChecklistCardContent } from "./checklist.js";
import { DashboardGeneralCardContent } from "./general.js";
import { DashboardHintCardContent } from "./hint.js";
import { DashboardMigrationCardContent } from "./migration.js";
import { DashboardServiceCloudCardContent } from "./serviceCloud.js";
import { useStores } from "../../../store/stores.js";
import { __ } from "../../../utils/i18n.js";
import { DateRangePicker } from "../../dateRangePicker.js";
import { StatsMainBarChart } from "../consent/stats/mainBar.js";

import type { FC } from "react";

const HREF_STATS = "#/consent";

const DashboardCards: FC = observer(() => {
    const { statsStore, optionStore, cookieStore, checklistStore } = useStores();
    const {
        others: {
            isPro,
            assetsUrl,
            hints: { dashboardTile },
        },
        dashboardMigration,
    } = optionStore;
    const {
        filters: { dates },
    } = statsStore;

    const [statsLiteInContainerRef, setStatsLiteInContainerRef] = useState<HTMLDivElement>();

    // Load initial content for all the dashboard cards
    useEffect(() => {
        // checklistStore.fetchChecklist(); // this is done in `header.tsx`
        cookieStore.groups.get();
        optionStore.fetchCurrentRevision();
    }, []);

    // Make the other cards `opacity` until a given amount of checklist items got resolved
    const otherCardsOpacity = checklistStore.completed.length < 3 || dashboardMigration ? 0.5 : 1;

    const generalCard = useMemo(
        () => (
            <Card
                style={{ margin: 10, opacity: otherCardsOpacity }}
                title={__("General")}
                className="rcb-dashboard-card-focus"
            >
                <DashboardGeneralCardContent />
            </Card>
        ),
        [otherCardsOpacity],
    );

    const migrationCard = useMemo(
        () =>
            dashboardMigration ? (
                <Card
                    style={{ margin: 10 }}
                    title={dashboardMigration.headline}
                    extra={
                        <a href="#" onClick={() => optionStore.dismissMigration()}>
                            {__("Dismiss this info")}
                        </a>
                    }
                >
                    <DashboardMigrationCardContent />
                </Card>
            ) : null,
        [dashboardMigration, optionStore],
    );

    const checklistCard = useMemo(
        () => (
            <Card
                style={{ margin: 10, opacity: dashboardMigration ? otherCardsOpacity : undefined }}
                title={__("Set up the cookie banner")}
                extra={
                    checklistStore.done ? null : (
                        <a href="#" onClick={() => checklistStore.toggleChecklistItem("all", true)}>
                            {__("I have already done all the steps")}
                        </a>
                    )
                }
            >
                <DashboardChecklistCardContent />
            </Card>
        ),
        [checklistStore.done, dashboardMigration],
    );

    const hintCards = useMemo(
        () =>
            dashboardTile.map(({ title, ...rest }) => (
                <Card
                    key={title}
                    style={{ margin: 10, opacity: otherCardsOpacity }}
                    title={title}
                    className="rcb-dashboard-card-focus"
                >
                    <DashboardHintCardContent {...rest} />
                </Card>
            )),
        [dashboardTile, otherCardsOpacity],
    );

    return checklistStore.items.length === 0 ? (
        // Show a spinner until all content is loaded (avoid flickering due to checklist cards movement)
        <Spin spinning style={{ marginTop: 15 }} />
    ) : (
        <Spin spinning={checklistStore.busyChecklist} style={{ marginTop: 15 }}>
            <Row>
                <Col xl={16} sm={16} xs={24}>
                    {migrationCard}
                    {checklistStore.done ? generalCard : checklistCard}
                    <Card
                        style={{ margin: 10, opacity: otherCardsOpacity }}
                        className="rcb-dashboard-card-focus"
                        title={__("Statistics")}
                        extra={
                            <>
                                <a href={HREF_STATS}>{__("More statistics")}</a>
                                &nbsp;&nbsp;&bull;&nbsp;&nbsp;
                                <DateRangePicker
                                    value={
                                        /* Ant design relies on moment 2.27 and typings are currently incompatible with other moment typings */ dates as any
                                    }
                                    disabled
                                />
                            </>
                        }
                    >
                        {isPro ? (
                            <StatsMainBarChart />
                        ) : (
                            <>
                                <UpsellModal
                                    title={__("Want to see detailed statistics about the consents of your visitors?")}
                                    inContainer
                                    inContainerElement={statsLiteInContainerRef}
                                    testDrive
                                    feature="dashboard-stats"
                                    description={__(
                                        "You can get several statistics about how your users use the cookie banner. This helps you to calculate the total number of users who do not want to be tracked, for example, by extrapolating data from Google Analytics.",
                                    )}
                                    showHints={false}
                                    showFomoCouponCounter={checklistStore.done}
                                />
                                <div
                                    ref={setStatsLiteInContainerRef}
                                    className="rcb-antd-modal-mount"
                                    style={{
                                        height: 600,
                                        backgroundImage: `url('${assetsUrl}dashboard-statistics-blured.png')`,
                                    }}
                                />
                            </>
                        )}
                    </Card>
                </Col>
                <Col xl={8} sm={8} xs={24}>
                    {checklistStore.done ? checklistCard : generalCard}
                    {hintCards}
                    <Card
                        style={{ margin: 10, opacity: otherCardsOpacity }}
                        title={__("Service Cloud")}
                        className="rcb-dashboard-card-focus"
                    >
                        <DashboardServiceCloudCardContent />
                    </Card>
                    <Card
                        style={{ margin: 10, opacity: otherCardsOpacity }}
                        title={__("Cache")}
                        className="rcb-dashboard-card-focus"
                    >
                        <DashboardCacheCardContent />
                    </Card>
                </Col>
            </Row>
        </Spin>
    );
});

export { DashboardCards };
