import dynamic from 'next/dynamic';
import { useMemo } from 'react';
import { useSelector } from 'react-redux';
import type { ApexOptions } from 'apexcharts';

import { IRootState } from '@/store';
import { getThemeChartColors, getThemeChartFont } from '@/lib/theme-colors';
import { journeyChartGrid, journeyChartInteract } from './journey-chart-options';

const ReactApexChart = dynamic(() => import('react-apexcharts'), { ssr: false });

export type TopPageRow = {
    path: string;
    count?: number;
    page_views?: number;
    sessions?: number;
};

interface JourneyTopPagesChartProps {
    pages?: TopPageRow[];
    limit?: number;
}

function shortPath(path: string, max = 36) {
    const p = String(path || '/');
    if (p.length <= max) return p;
    return `${p.slice(0, max - 1)}…`;
}

const JourneyTopPagesChart = ({ pages = [], limit = 10 }: JourneyTopPagesChartProps) => {
    const isDark = useSelector(
        (state: IRootState) => state.themeConfig.theme === 'dark' || state.themeConfig.isDarkMode
    );
    const colorScheme = useSelector((state: IRootState) => state.themeConfig.colorScheme);
    const chartColors = getThemeChartColors(colorScheme);
    const rows = useMemo(
        () =>
            [...(pages || [])]
                .sort((a, b) => Number(b.sessions ?? b.count ?? b.page_views) - Number(a.sessions ?? a.count ?? a.page_views))
                .slice(0, limit),
        [pages, limit]
    );
    const categories = useMemo(() => rows.map((r) => shortPath(r.path)), [rows]);
    const seriesData = useMemo(
        () => rows.map((r) => Number(r.sessions ?? r.count ?? r.page_views) || 0),
        [rows]
    );
    const fullPaths = useMemo(() => rows.map((r) => r.path), [rows]);

    const options = useMemo<ApexOptions>(
        () => ({
            chart: {
                type: 'bar',
                fontFamily: getThemeChartFont(colorScheme),
                ...journeyChartInteract,
            },
            plotOptions: {
                bar: {
                    horizontal: true,
                    borderRadius: 4,
                    barHeight: '70%',
                },
            },
            colors: [chartColors[0]],
            dataLabels: { enabled: false },
            xaxis: {
                categories,
                labels: { style: { fontSize: '11px' } },
                axisBorder: { show: !isDark },
                axisTicks: { show: !isDark },
            },
            yaxis: {
                labels: { style: { fontSize: '11px' } },
            },
            grid: journeyChartGrid(isDark),
            tooltip: {
                y: {
                    formatter: (val, opts) => {
                        const idx = opts?.dataPointIndex ?? 0;
                        const path = fullPaths[idx] || '';
                        return `${val} sessions · ${path}`;
                    },
                },
            },
        }),
        [categories, fullPaths, isDark, chartColors, colorScheme]
    );

    if (!rows.length) {
        return <p className="text-sm text-gray-400">Belum ada data landing page di rentang ini.</p>;
    }

    return (
        <ReactApexChart
            options={options}
            series={[{ name: 'Landings', data: seriesData }]}
            type="bar"
            height={Math.max(220, rows.length * 28 + 40)}
        />
    );
};

export default JourneyTopPagesChart;
