import { useTranslation } from '@/hooks/use-translation';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, router, usePage } from '@inertiajs/react';
import React, { useEffect, useRef } from 'react';
import { FiltersCard } from './filters-card';
import {
    CategoryBars,
    EmptyState,
    HousekeeperCleanlinessPanel,
    KpiCards,
    MonthlyTrendChart,
    PropertyRankingTable,
    RatingDistributionChart,
    SourceComparisonChart,
    SourceDonut,
    StatsSection,
    type CategoryAverage,
    type DistributionBucket,
    type HeroMetrics,
    type HousekeeperCleanliness,
    type PropertyRank,
    type SourceAverage,
    type SourceBreakdownPoint,
    type TrendPoint,
} from './stats-widgets';
import { TabsSwitcher, type CurrentFilters } from './tabs-switcher';

interface StatsPayload {
    hero: HeroMetrics;
    trend: TrendPoint[];
    sourceBreakdown: SourceBreakdownPoint[];
    topProperties: PropertyRank[];
    bottomProperties: PropertyRank[];
    categoryAverages: CategoryAverage[];
    ratingDistribution: DistributionBucket[];
    sourceAverages: SourceAverage[];
    housekeeperCleanliness: HousekeeperCleanliness;
}

interface PageProps {
    stats: StatsPayload;
    dateFrom: string;
    dateTo: string;
    logements: { id: number; name: string; internal_name?: string | null; [key: string]: unknown }[];
    coHosts: { id: string | number; name: string }[];
    sources: string[];
    auth: { isAdmin: boolean; permissions: string[] };
    currentFilters?: CurrentFilters;
    [key: string]: unknown;
}

export default function Stats() {
    const { t } = useTranslation();
    const { stats, dateFrom, dateTo, logements, coHosts, sources, auth, currentFilters } =
        usePage<PageProps>().props;

    const breadcrumbs: BreadcrumbItem[] = [
        { title: t('reviews', 'reviews'), href: '/reviews' },
        { title: t('reviews', 'view_stats'), href: '/reviews/stats' },
    ];

    const [coHost, setCoHost] = React.useState(currentFilters?.coHost ?? '');
    const [dateRange, setDateRange] = React.useState({ from: dateFrom, to: dateTo });
    const [state, setState] = React.useState<string>(currentFilters?.state ?? 'tous');
    const [logement, setLogement] = React.useState<string>(currentFilters?.logement ?? '');
    const [minRating, setMinRating] = React.useState<string>(currentFilters?.minRating ?? '0');
    const [source, setSource] = React.useState<string>(currentFilters?.source ?? 'tous');

    // Same first-render guard as the list view — keeps the default date range from polluting
    // the URL and inadvertently filtering out reviews with NULL/older ru_created_at.
    const isFirstRender = useRef(true);

    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }
        const delayDebounceFn = setTimeout(() => {
            const data: Record<string, string | object | undefined> = { dateRange, state, logement, minRating, source };
            if (coHost) data.coHost = coHost;
            router.get(route('reviews.stats'), data as never, { preserveState: true, replace: true });
        }, 200);

        return () => clearTimeout(delayDebounceFn);
    }, [dateRange, state, logement, minRating, source, coHost]);

    const noData = stats.hero.total === 0;

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={t('reviews', 'view_stats')} />
            <div className="flex h-full flex-1 flex-col rounded-xl">
                <div className="bg-secondary rounded-b-2xl px-2 pb-1 lg:px-4">
                    <FiltersCard
                        filters={{
                            dateRange,
                            setDateRange,
                            state,
                            setState,
                            logement,
                            setLogement,
                            minRating,
                            setMinRating,
                            source,
                            setSource,
                            coHost,
                            setCoHost,
                        }}
                        logements={logements}
                        coHosts={coHosts}
                        sources={sources}
                        isAdmin={auth.isAdmin}
                        refreshRoute="reviews.stats"
                        t={t}
                    />
                </div>
                <div className="space-y-4 px-2 lg:px-4">
                    <TabsSwitcher active="stats" filters={currentFilters ?? {}} t={t} />

                    {noData ? (
                        <EmptyState message={t('reviews', 'no_reviews')} />
                    ) : (
                        <>
                            {/* Row 1 — KPI hero */}
                            <KpiCards hero={stats.hero} t={t} />

                            {/* Row 2 — Trend + Source donut */}
                            <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
                                <StatsSection title={t('reviews', 'monthly_trend')} className="lg:col-span-2">
                                    <MonthlyTrendChart data={stats.trend} t={t} />
                                </StatsSection>
                                <StatsSection title={t('reviews', 'source_breakdown')}>
                                    <SourceDonut data={stats.sourceBreakdown} t={t} />
                                </StatsSection>
                            </div>

                            {/* Row 3 — Top + Bottom properties */}
                            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                                <PropertyRankingTable
                                    title={t('reviews', 'top_properties')}
                                    rows={stats.topProperties}
                                    tone="positive"
                                    t={t}
                                />
                                <PropertyRankingTable
                                    title={t('reviews', 'bottom_properties')}
                                    rows={stats.bottomProperties}
                                    tone="negative"
                                    t={t}
                                />
                            </div>

                            {/* Row 4 — Categories breakdown */}
                            <StatsSection title={t('reviews', 'category_averages')}>
                                <CategoryBars data={stats.categoryAverages} t={t} />
                            </StatsSection>

                            {/* Row 4b — Housekeeper (femmes de ménage) cleanliness scoring */}
                            <StatsSection title={t('reviews', 'housekeeper_cleanliness')}>
                                <HousekeeperCleanlinessPanel data={stats.housekeeperCleanliness} t={t} />
                            </StatsSection>

                            {/* Row 5 — Distribution + Source comparison */}
                            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                                <StatsSection title={t('reviews', 'rating_distribution')}>
                                    <RatingDistributionChart data={stats.ratingDistribution} t={t} />
                                </StatsSection>
                                <StatsSection title={t('reviews', 'source_comparison')}>
                                    <SourceComparisonChart data={stats.sourceAverages} t={t} />
                                </StatsSection>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </AppLayout>
    );
}
