import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useTranslation } from '@/hooks/use-translation';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { ArrowLeft, BarChart3, CalendarCheck, Clock, Coins, Home, TrendingDown, TrendingUp } from 'lucide-react';
import { useMemo } from 'react';
import KpiHeroCard from './components/kpi-hero-card';
import { getKpiColumns } from './components/kpi-columns';
import KpiStatTile from './components/kpi-stat-tile';
import OccupancyBarList from './components/occupancy-bar-list';
import RevenueChart from './components/revenue-chart';
import YoyComparison from './components/yoy-comparison';
import { formatTnd, type KpiPageProps } from './components/kpi-types';

export default function Kpi() {
    const { headline, best, worst, topByOccupancy, rows, period, criterion, comparison, snapshot_at, coHosts, filters, auth } =
        usePage<KpiPageProps>().props;
    const { t, locale } = useTranslation();

    const breadcrumbs: BreadcrumbItem[] = [
        { title: t('properties.index', 'accommodation_management'), href: '/logements' },
        { title: t('properties.kpi', 'page_title'), href: '/logements/kpi' },
    ];

    const columns = useMemo(() => getKpiColumns(t, locale), [t, locale]);

    // "Les moins occupés" — derived client-side from the full rows (available > 0, ascending).
    const leastOccupiedList = useMemo(
        () =>
            [...rows]
                .filter((r) => r.available_nights > 0)
                .sort((a, b) => a.occupancy_rate - b.occupancy_rate)
                .slice(0, 8),
        [rows],
    );

    function applyFilters(next: Partial<typeof filters>) {
        const merged = { ...filters, ...next };
        const params: Record<string, string> = {
            period: merged.period,
            criterion: merged.criterion,
        };
        if (merged.coHost) params.coHost = merged.coHost;
        if (merged.period === 'custom') {
            if (merged.from) params.from = merged.from;
            if (merged.to) params.to = merged.to;
        }
        router.get(route('logements.kpi'), params, { preserveState: true, preserveScroll: true, replace: true });
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={t('properties.kpi', 'page_title')} />
            <div className="flex h-full flex-1 flex-col gap-4 p-4">
                <div className="container mx-auto w-full">
                    {/* Header */}
                    <div className="flex flex-wrap items-start justify-between gap-3">
                        <div>
                            <h1 className="flex items-center gap-2 text-2xl font-bold">
                                <BarChart3 className="text-secondary h-6 w-6" />
                                {t('properties.kpi', 'page_title')}
                            </h1>
                            <p className="text-muted-foreground mt-1 max-w-2xl text-sm">{t('properties.kpi', 'page_subtitle')}</p>
                        </div>
                        <Button variant="outline" asChild>
                            <Link href={route('logements')}>
                                <ArrowLeft className="h-4 w-4" />
                                {t('properties.kpi', 'back_to_list')}
                            </Link>
                        </Button>
                    </div>

                    {/* Filters */}
                    <div className="mt-4 flex flex-wrap items-end gap-3 rounded-xl border bg-white/80 p-3 shadow-sm">
                        <div className="flex flex-col gap-1">
                            <label className="text-muted-foreground text-xs">{t('properties.kpi', 'period')}</label>
                            <Select value={filters.period} onValueChange={(v) => applyFilters({ period: v })}>
                                <SelectTrigger className="w-[190px] bg-white">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectGroup>
                                        <SelectItem value="this_year">{t('properties.kpi', 'period_this_year')}</SelectItem>
                                        <SelectItem value="last_12_months">{t('properties.kpi', 'period_last_12_months')}</SelectItem>
                                        <SelectItem value="all_time">{t('properties.kpi', 'period_all_time')}</SelectItem>
                                        <SelectItem value="custom">{t('properties.kpi', 'period_custom')}</SelectItem>
                                    </SelectGroup>
                                </SelectContent>
                            </Select>
                        </div>

                        {filters.period === 'custom' && (
                            <>
                                <div className="flex flex-col gap-1">
                                    <label className="text-muted-foreground text-xs">{t('properties.kpi', 'from')}</label>
                                    <input
                                        type="date"
                                        defaultValue={filters.from ?? ''}
                                        onChange={(e) => applyFilters({ from: e.target.value })}
                                        className="h-9 rounded-md border bg-white px-2 text-sm"
                                    />
                                </div>
                                <div className="flex flex-col gap-1">
                                    <label className="text-muted-foreground text-xs">{t('properties.kpi', 'to')}</label>
                                    <input
                                        type="date"
                                        defaultValue={filters.to ?? ''}
                                        onChange={(e) => applyFilters({ to: e.target.value })}
                                        className="h-9 rounded-md border bg-white px-2 text-sm"
                                    />
                                </div>
                            </>
                        )}

                        <div className="flex flex-col gap-1">
                            <label className="text-muted-foreground text-xs">{t('properties.kpi', 'criterion')}</label>
                            <Select value={filters.criterion} onValueChange={(v) => applyFilters({ criterion: v })}>
                                <SelectTrigger className="w-[170px] bg-white">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectGroup>
                                        <SelectItem value="composite">{t('properties.kpi', 'criterion_composite')}</SelectItem>
                                        <SelectItem value="revenue">{t('properties.kpi', 'criterion_revenue')}</SelectItem>
                                        <SelectItem value="occupancy">{t('properties.kpi', 'criterion_occupancy')}</SelectItem>
                                    </SelectGroup>
                                </SelectContent>
                            </Select>
                        </div>

                        {auth?.isAdmin && (
                            <div className="flex flex-col gap-1">
                                <label className="text-muted-foreground text-xs">{t('properties.kpi', 'franchise')}</label>
                                <Select value={filters.coHost ?? 'landlord'} onValueChange={(v) => applyFilters({ coHost: v })}>
                                    <SelectTrigger className="w-[200px] bg-white">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectGroup>
                                            <SelectItem value="landlord">{t('properties.kpi', 'the_landlord')}</SelectItem>
                                            {coHosts.map((c) => (
                                                <SelectItem key={c.id} value={c.id}>
                                                    {c.name}
                                                </SelectItem>
                                            ))}
                                            <SelectItem value="all">{t('properties.kpi', 'all_label')}</SelectItem>
                                        </SelectGroup>
                                    </SelectContent>
                                </Select>
                            </div>
                        )}

                        <div className="text-muted-foreground ml-auto flex flex-col items-end gap-0.5 self-center text-xs">
                            <span>
                                {period.from} → {period.to}
                            </span>
                            <span className="flex items-center gap-1">
                                <Clock className="h-3 w-3" />
                                {snapshot_at
                                    ? `${t('properties.kpi', 'data_as_of')} ${new Date(snapshot_at).toLocaleString(locale)}`
                                    : t('properties.kpi', 'data_live')}
                            </span>
                        </div>
                    </div>

                    {/* Hero zone */}
                    <div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                        <KpiHeroCard variant="champion" row={best} criterion={criterion.key} locale={locale} t={t} />
                        <KpiHeroCard variant="attention" row={worst} criterion={criterion.key} locale={locale} t={t} />
                    </div>

                    {/* Headline KPI tiles */}
                    <div className="mt-4 grid grid-cols-2 gap-3 lg:grid-cols-5">
                        <KpiStatTile
                            label={t('properties.kpi', 'total_revenue')}
                            value={headline.total_revenue_formatted}
                            icon={Coins}
                            accent="text-emerald-600"
                            hint={t('properties.kpi', 'revenue_explain')}
                        />
                        <KpiStatTile
                            label={t('properties.kpi', 'avg_occupancy')}
                            value={`${headline.avg_occupancy}`}
                            unit="%"
                            icon={TrendingUp}
                            accent="text-sky-600"
                            hint={t('properties.kpi', 'occupancy_explain')}
                        />
                        <KpiStatTile
                            label={t('properties.kpi', 'total_nights')}
                            value={headline.total_nights.toLocaleString(locale)}
                            unit={t('properties.kpi', 'unit_nights')}
                            icon={CalendarCheck}
                            accent="text-indigo-600"
                        />
                        <KpiStatTile
                            label={t('properties.kpi', 'total_reservations')}
                            value={headline.total_reservations.toLocaleString(locale)}
                            icon={CalendarCheck}
                            accent="text-violet-600"
                        />
                        <KpiStatTile
                            label={t('properties.kpi', 'properties_count')}
                            value={headline.property_count.toLocaleString(locale)}
                            icon={Home}
                            accent="text-secondary"
                        />
                    </div>

                    {/* Year-over-year comparison (curves) */}
                    {comparison && <YoyComparison comparison={comparison} locale={locale} t={t} />}

                    {/* Top 20 occupancy + Revenue chart */}
                    <div className="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-2">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2 text-base">
                                    <TrendingUp className="h-4 w-4 text-emerald-600" />
                                    {t('properties.kpi', 'top_occupancy_title')}
                                </CardTitle>
                                <CardDescription>{t('properties.kpi', 'occupancy_explain')}</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <OccupancyBarList items={topByOccupancy} emptyLabel={t('properties.kpi', 'no_data_period')} podium />
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2 text-base">
                                    <Coins className="h-4 w-4 text-emerald-600" />
                                    {t('properties.kpi', 'revenue_chart_title')}
                                </CardTitle>
                                <CardDescription>{t('properties.kpi', 'revenue_chart_caption')}</CardDescription>
                            </CardHeader>
                            <CardContent>
                                <RevenueChart rows={rows} locale={locale} t={t} />
                            </CardContent>
                        </Card>
                    </div>

                    {/* Least occupied */}
                    <Card className="mt-4">
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2 text-base">
                                <TrendingDown className="h-4 w-4 text-rose-600" />
                                {t('properties.kpi', 'least_occupied_title')}
                            </CardTitle>
                            <CardDescription>{t('properties.kpi', 'least_occupied_caption')}</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <OccupancyBarList items={leastOccupiedList} emptyLabel={t('properties.kpi', 'no_data_period')} />
                        </CardContent>
                    </Card>

                    {/* Detailed sortable table */}
                    <Card className="mt-4">
                        <CardHeader>
                            <CardTitle className="text-base">{t('properties.kpi', 'ranking_title')}</CardTitle>
                            <CardDescription>{t('properties.kpi', 'ranking_caption')}</CardDescription>
                        </CardHeader>
                        <CardContent>
                            {rows.length === 0 ? (
                                <div className="text-muted-foreground py-8 text-center text-sm">{t('properties.kpi', 'no_data_period')}</div>
                            ) : (
                                <DataTable columns={columns} data={rows} />
                            )}
                        </CardContent>
                    </Card>

                    <p className="text-muted-foreground mt-3 text-center text-xs">
                        {t('properties.kpi', 'total_revenue')}: {formatTnd(headline.total_revenue, locale)}
                    </p>
                </div>
            </div>
        </AppLayout>
    );
}
