// JavaScript
import Header from "./Analytics/Header";
import { formatDate } from "../includes/functions";
import UsageSummary from "./Analytics/UsageSummary";
import ActivationChart from "./Analytics/ActivationChart";
import ActivationDeactivation from "./Analytics/ActivationDeactivation";
import PageViews from "./Analytics/PageViews";
import Feedbacks from "./Analytics/Feedbacks";
import ProModal from "./ProModal";

const { useState, useEffect, useRef } = React;

const { isPro, settings } = dracula;

const DEBOUNCE_MS = 350;

// Precompute default dates once
const DEFAULT_DATES = (() => {
    const now = new Date();
    const lastMonth = new Date(now);
    lastMonth.setMonth(lastMonth.getMonth() - 1);
    return {
        start: formatDate(lastMonth),
        end: formatDate(now),
    };
})();

// Static sample data for free version preview
const SAMPLE_DATA = {
    total_user: 1200,
    dark_mode_user: 800,
    total_view: 3000,
    dark_view: 2200,
    total_activation: 180,
    total_deactivation: 70,
    activations: [
        { date: "2023-01-01", count: 10 },
        { date: "2023-01-02", count: 20 },
        { date: "2023-01-03", count: 22 },
        { date: "2023-01-04", count: 40 },
        { date: "2023-01-05", count: 30 },
        { date: "2023-01-06", count: 50 },
        { date: "2023-01-07", count: 45 },
        { date: "2023-01-08", count: 60 },
    ],
    feedbacks: [
        {
            date: "2023-01-01",
            message:
                "The dark mode is a game-changer! It's so much easier on my eyes during nighttime browsing. Thank you!",
        },
        {
            date: "2023-01-02",
            message:
                "I love the dark mode feature! It seamlessly integrates with the rest of the design.",
        },
        {
            date: "2023-01-03",
            message:
                "Switching to dark mode has significantly improved my reading experience, especially in dimly lit environments.",
        },
        {
            date: "2023-01-04",
            message:
                "Fantastic addition! The dark mode gives the website a modern and sleek look.",
        },
        {
            date: "2023-01-05",
            message:
                "Kudos on introducing the dark mode. It's perfect for those late-night sessions without straining my eyes.",
        },
        {
            date: "2023-01-06",
            message:
                "The transition to dark mode is smooth, and the color contrast is just right. Well done!",
        },
        {
            date: "2023-01-07",
            message:
                "I've always preferred dark themes, and your dark mode doesn't disappoint. It's one of the best I've seen.",
        },
    ],
};

export default function Analytics() {
    const [loading, setLoading] = useState(false);
    const [startDate, setStartDate] = useState(DEFAULT_DATES.start);
    const [endDate, setEndDate] = useState(DEFAULT_DATES.end);
    const [data, setData] = useState(isPro ? null : SAMPLE_DATA);
    const [error, setError] = useState(null);

    const debounceRef = useRef(null);
    const xhrRef = useRef(null);

    // Cleanup on unmount: abort any in-flight request and clear debounce
    useEffect(() => {
        return () => {
            if (debounceRef.current) {
                clearTimeout(debounceRef.current);
            }
            if (xhrRef.current && typeof xhrRef.current.abort === "function") {
                xhrRef.current.abort();
            }
        };
    }, []);

    useEffect(() => {
        if (!isPro) return;

        // Debounce to prevent spamming the server when dates change rapidly
        if (debounceRef.current) {
            clearTimeout(debounceRef.current);
        }

        setError(null);
        setLoading(true);

        debounceRef.current = setTimeout(() => {
            // Abort previous request (if any) to avoid race conditions
            if (xhrRef.current && typeof xhrRef.current.abort === "function") {
                xhrRef.current.abort();
            }

            setData(null);

            xhrRef.current = wp.ajax.post("dracula_get_analytics", {
                start_date: startDate,
                end_date: endDate,
            });

            xhrRef.current
                .done((response) => {
                    setData(response);
                })
                .fail((jqXHR) => {
                    // Ignore abort errors
                    if (jqXHR && jqXHR.statusText === "abort") return;
                    setError(wp.i18n.__("Failed to load analytics. Please try again.", "dracula-dark-mode"));
                    // Keep a console for debugging without breaking UI
                    // eslint-disable-next-line no-console
                    console.error(jqXHR);
                })
                .always(() => {
                    setLoading(false);
                });
        }, DEBOUNCE_MS);

        // Clear pending debounce on param changes
        return () => {
            if (debounceRef.current) {
                clearTimeout(debounceRef.current);
            }
        };
    }, [startDate, endDate]);

    const shouldShowFeedbacks = !isPro || !!(settings && settings.enableFeedback);

    return (
        <div className="dracula-analytics">
            <Header
                startDate={startDate}
                endDate={endDate}
                setStartDate={setStartDate}
                setEndDate={setEndDate}
                setData={setData}
            />

            {loading && <div className="dracula-spinner spinner-large" role="status" aria-live="polite" />}

            {error && (
                <div className="notice notice-error" role="alert">
                    <p>{error}</p>
                </div>
            )}

            {!!data && (
                <>
                    <UsageSummary data={data} />
                    <PageViews data={data} />
                    <ActivationDeactivation data={data} />
                    <ActivationChart data={data} />
                    {shouldShowFeedbacks && (
                        <Feedbacks data={data} setData={setData} startDate={startDate} endDate={endDate} />
                    )}
                </>
            )}

            {isPro && !loading && !error && !data && (
                <div className="notice notice-info">
                    <p>{wp.i18n.__("No analytics found for the selected date range.", "dracula-dark-mode")}</p>
                </div>
            )}

            {!isPro && (
                <ProModal
                    isDismissable={false}
                    text={wp.i18n.__("Upgrade to PRO to access dark mode usage analytics.", "dracula-dark-mode")}
                />
            )}
        </div>
    );
}
