"use client"

import { KPICard } from "@/components/ui/kpi-card"
import { Skeleton } from "@/components/ui/skeleton"
import type {
    DashboardKpis,
    DashboardPacingMetrics,
    DashboardSalesDailyMetrics,
    MonthTargetLagOverride,
} from "@/api/rtk/dashboard-api"
import { formatMoney } from "@/components/sales-targets/sales-targets-helpers"
import { useDashboardKpisQuery } from "@/features/dashboard/hooks/use-dashboard-section-queries"
import {
    isDashboardPacingLoading,
    isDashboardSalesDailyLoading,
    isDashboardSectionLoading,
} from "@/features/dashboard/hooks/dashboard-query-status"

interface KPI {
    label: string
    value: string
    change: string
    up: boolean
    sub: string
}

function kpisFromApi(api: DashboardKpis): KPI[] {
    const c = api.change ?? {}
    const fmt = (n: number) => (n >= 0 ? `+${n.toFixed(1)}%` : `${n.toFixed(1)}%`)
    return [
        { label: "Total Revenue", value: api.totalRevenueFormatted, change: typeof c.revenue === "number" ? fmt(c.revenue) : "—", up: (c.revenue ?? 0) >= 0, sub: "all time" },
        { label: "Deals Closed", value: api.dealsClosedFormatted, change: typeof c.dealsClosed === "number" ? fmt(c.dealsClosed) : "—", up: (c.dealsClosed ?? 0) >= 0, sub: "all time" },
        { label: "Avg Deal Size", value: api.avgDealSizeFormatted, change: typeof c.avgDealSize === "number" ? fmt(c.avgDealSize) : "—", up: (c.avgDealSize ?? 0) >= 0, sub: "all time" },
        { label: "Total Transaction Amount", value: api.totalTransactionAmountFormatted, change: typeof c.totalTransactionAmount === "number" ? fmt(c.totalTransactionAmount) : "—", up: (c.totalTransactionAmount ?? 0) >= 0, sub: "sum of transactions" },
        { label: "Quota Attainment", value: api.quotaAttainment != null ? `${api.quotaAttainment}%` : "—", change: typeof c.quotaAttainment === "number" ? `+${c.quotaAttainment}%` : "—", up: true, sub: "team average" },
    ]
}

export function KpiGridSkeleton() {
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
            {Array.from({ length: 5 }).map((_, i) => (
                <div
                    key={i}
                    className="flex flex-col gap-2 rounded-xl border border-border p-4"
                >
                    <Skeleton className="h-3 w-24 rounded bg-border/70" />
                    <Skeleton className="h-6 w-16 rounded bg-border/60" />
                    <Skeleton className="h-3 w-20 rounded bg-border/50" />
                </div>
            ))}
        </div>
    )
}

export function KPIGrid({ kpis: apiKpis, isLoading }: { kpis?: DashboardKpis; isLoading?: boolean }) {
    if (isLoading || apiKpis === undefined) {
        return <KpiGridSkeleton />
    }
    const kpis = kpisFromApi(apiKpis)
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
            {kpis.map((kpi) => (
                <KPICard
                    key={kpi.label}
                    label={kpi.label}
                    value={kpi.value}
                    change={kpi.change}
                    isUp={kpi.up}
                    subtext={kpi.sub}
                />
            ))}
        </div>
    )
}

function pacingKpisFromApi(pacing: DashboardPacingMetrics): KPI[] {
    const dailyAvgUp = (pacing.dailyAvgPct ?? 100) >= 100
    const dailyAvgDelta =
        pacing.dailyAvgPct != null
            ? `${pacing.dailyAvgPct >= 100 ? "+" : ""}${(pacing.dailyAvgPct - 100).toFixed(1)} pts`
            : undefined

    return [
        {
            label: "Revenue Req. / Day",
            value: pacing.revenueRequiredPerDayFormatted,
            change: "",
            up: true,
            sub: pacing.remainingDays != null
                ? `${pacing.remainingDays} remaining days`
                : "monthly period only",
        },
        {
            label: "Daily Avg Achieved",
            value: pacing.dailyAvgAchievedFormatted,
            change: "",
            up: true,
            sub: `${pacing.periodLabel} · ${pacing.daysTracked} days`,
        },
        {
            label: "Daily AVG %",
            value: pacing.dailyAvgPctFormatted,
            change: dailyAvgDelta ?? "",
            up: dailyAvgUp,
            sub: "vs last quarter daily avg",
        },
        {
            label: "Est. Revenue (Daily Avg)",
            value: pacing.estimatedRevenueFormatted,
            change: "",
            up: true,
            sub: "annualized projection",
        },
    ]
}

export function PacingKpiGridSkeleton() {
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => (
                <div
                    key={i}
                    className="flex flex-col gap-2 rounded-xl border border-border p-4"
                >
                    <Skeleton className="h-3 w-24 rounded bg-border/70" />
                    <Skeleton className="h-6 w-16 rounded bg-border/60" />
                    <Skeleton className="h-3 w-20 rounded bg-border/50" />
                </div>
            ))}
        </div>
    )
}

export function PacingKpiGrid({
    pacing,
    isLoading,
}: {
    pacing?: DashboardPacingMetrics
    isLoading?: boolean
}) {
    if (isLoading || pacing === undefined) {
        return <PacingKpiGridSkeleton />
    }
    const kpis = pacingKpisFromApi(pacing)
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {kpis.map((kpi) => (
                <KPICard
                    key={kpi.label}
                    label={kpi.label}
                    value={kpi.value}
                    change={kpi.change || undefined}
                    isUp={kpi.up}
                    subtext={kpi.sub}
                />
            ))}
        </div>
    )
}

function formatUtcDateLabel(dateKey: string | null | undefined): string {
    if (!dateKey) return "—"
    const [year, month, day] = dateKey.split("-").map(Number)
    if (!year || !month || !day) return dateKey
    const monthNames = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ]
    return `${monthNames[month - 1] ?? month} ${day}, ${year}`
}

function salesDailyDeltaSubtext(
    current: number,
    previous: number,
    currentLabel: string,
): string {
    if (previous <= 0) {
        return current > 0
            ? `${currentLabel} · new vs last month`
            : `${currentLabel} · no sales yet`
    }
    const pct = ((current - previous) / previous) * 100
    const sign = pct >= 0 ? "+" : ""
    return `${currentLabel} · ${sign}${pct.toFixed(1)}% vs last month`
}

function monthTargetLagKpi(
    lag: number,
    target: number,
    attained: number,
    monthLabel: string,
): KPI {
    const onTarget = lag <= 0
    return {
        label: "Month Target Lag",
        value: formatMoney(lag),
        change: "",
        up: onTarget,
        sub: onTarget
            ? `${monthLabel} · ${formatMoney(attained)} of ${formatMoney(target)}`
            : `${monthLabel} · ${formatMoney(attained)} attained · ${formatMoney(target)} target`,
    }
}

function resolveMonthTargetLagKpi(
    salesDaily: DashboardSalesDailyMetrics,
    override?: MonthTargetLagOverride,
): KPI | null {
    if (override && override.target > 0) {
        return monthTargetLagKpi(
            override.lag,
            override.target,
            override.attained,
            override.monthLabel,
        )
    }
    if (salesDaily.monthlyTarget == null || salesDaily.monthlyTarget <= 0) {
        return null
    }
    return monthTargetLagKpi(
        salesDaily.monthTargetLag ?? 0,
        salesDaily.monthlyTarget,
        salesDaily.monthToDateAchieved,
        salesDaily.monthTargetLabel,
    )
}

function salesDailyKpisFromApi(
    salesDaily: DashboardSalesDailyMetrics,
    monthTargetLag?: MonthTargetLagOverride,
): KPI[] {
    const todayDay = new Date().getUTCDate()
    const lastMonthWindow = `${salesDaily.lastMonthLabel} · days 1–${todayDay}`
    const bestMonthSub = salesDaily.bestMonthTillSameDate
        ? `${salesDaily.bestMonthTillSameDate.label} · days 1–${todayDay}`
        : "no historical data"
    const lagKpi = resolveMonthTargetLagKpi(salesDaily, monthTargetLag)

    return [
        {
            label: "Lowest Sales Per Day",
            value: salesDaily.lowestSalesPerDayFormatted,
            change: "",
            up: true,
            sub: salesDaily.lowestSalesPerDayDate
                ? formatUtcDateLabel(salesDaily.lowestSalesPerDayDate)
                : "no paid days yet",
        },
        {
            label: "Average Sales Per Day",
            value: salesDaily.averageSalesPerDayFormatted,
            change: "",
            up: true,
            sub: `${salesDaily.daysTracked} days tracked`,
        },
        {
            label: "Last Month till Same Day",
            value: salesDaily.lastMonthTillSameDayFormatted,
            change: "",
            up: salesDaily.currentMonthTillSameDay >= salesDaily.lastMonthTillSameDay,
            sub: salesDailyDeltaSubtext(
                salesDaily.currentMonthTillSameDay,
                salesDaily.lastMonthTillSameDay,
                lastMonthWindow,
            ),
        },
        {
            label: "Best Month till Same Date",
            value: salesDaily.bestMonthTillSameDate?.amountFormatted ?? "—",
            change: "",
            up: true,
            sub: bestMonthSub,
        },
        {
            label: "Best per Month per Day",
            value: salesDaily.bestSingleDay?.amountFormatted ?? "—",
            change: "",
            up: true,
            sub: salesDaily.bestSingleDay
                ? formatUtcDateLabel(salesDaily.bestSingleDay.date)
                : "no record day yet",
        },
        ...(lagKpi ? [lagKpi] : []),
    ]
}

export function SalesDailyKpiGridSkeleton({ cardCount = 6 }: { cardCount?: number }) {
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
            {Array.from({ length: cardCount }).map((_, i) => (
                <div
                    key={i}
                    className="flex flex-col gap-2 rounded-xl border border-border p-4"
                >
                    <Skeleton className="h-3 w-24 rounded bg-border/70" />
                    <Skeleton className="h-6 w-16 rounded bg-border/60" />
                    <Skeleton className="h-3 w-20 rounded bg-border/50" />
                </div>
            ))}
        </div>
    )
}

export function SalesDailyKpiGrid({
    salesDaily,
    isLoading,
    monthTargetLag,
    skeletonCardCount = 6,
}: {
    salesDaily?: DashboardSalesDailyMetrics
    isLoading?: boolean
    monthTargetLag?: MonthTargetLagOverride
    skeletonCardCount?: number
}) {
    if (isLoading || salesDaily === undefined) {
        return <SalesDailyKpiGridSkeleton cardCount={skeletonCardCount} />
    }
    const kpis = salesDailyKpisFromApi(salesDaily, monthTargetLag)
    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
            {kpis.map((kpi) => (
                <KPICard
                    key={kpi.label}
                    label={kpi.label}
                    value={kpi.value}
                    change={kpi.change || undefined}
                    isUp={kpi.up}
                    subtext={kpi.sub}
                />
            ))}
        </div>
    )
}

const dashboardKpisQueryOptions = { refetchOnMount: "always" as const };

/** KPI row wired to `/dashboard/kpis` with skeleton while loading. */
export function DashboardKpiGrid() {
    const { data: kpis, isPending, isFetching } = useDashboardKpisQuery(
        dashboardKpisQueryOptions,
    )
    const loading = isDashboardSectionLoading(isPending, isFetching, kpis)
    return <KPIGrid kpis={kpis} isLoading={loading} />
}

/** Pacing KPI row (second row) wired to `/dashboard/kpis` `pacing` payload. */
export function DashboardPacingKpiGrid() {
    const { data: kpis, isPending, isFetching } = useDashboardKpisQuery(
        dashboardKpisQueryOptions,
    )
    const loading = isDashboardPacingLoading(isPending, isFetching, kpis?.pacing)
    return <PacingKpiGrid pacing={kpis?.pacing} isLoading={loading} />
}

/** Sales-daily benchmark row wired to `/dashboard/kpis` `salesDaily` payload. */
export function DashboardSalesDailyKpiGrid() {
    const { data: kpis, isPending, isFetching } = useDashboardKpisQuery(
        dashboardKpisQueryOptions,
    )
    const loading = isDashboardSalesDailyLoading(
        isPending,
        isFetching,
        kpis?.salesDaily,
    )
    return <SalesDailyKpiGrid salesDaily={kpis?.salesDaily} isLoading={loading} />
}

/** Sales-daily benchmarks plus month target lag for the selected sales-target period. */
export function SalesTargetsSalesDailyKpiGrid({
    monthTargetLag,
}: {
    monthTargetLag?: MonthTargetLagOverride
}) {
    const { data: kpis, isPending, isFetching } = useDashboardKpisQuery(
        dashboardKpisQueryOptions,
    )
    const loading = isDashboardSalesDailyLoading(
        isPending,
        isFetching,
        kpis?.salesDaily,
    )
    return (
        <SalesDailyKpiGrid
            salesDaily={kpis?.salesDaily}
            isLoading={loading}
            monthTargetLag={monthTargetLag}
            skeletonCardCount={6}
        />
    )
}
