"use client"

import * as React from "react"
import {
    ResponsiveContainer,
    PieChart,
    Pie,
    Cell,
    Tooltip,
    Legend,
    type TooltipProps,
} from "recharts"
import { ReportRange, RevenueSlice } from "./types"
import { formatReportsPeriodLabel } from "./reports-period-label"
import { NoDataFound } from "@/components/ui/no-data-found"
import { cn } from "@/lib/utils"

export type ReportsRevenueDonutChartProps = {
    data: RevenueSlice[]
    range: ReportRange
    title: string
    subtitleSuffix: string
    emptyMessage: string
    emptyDescription: string
    compact?: boolean
    className?: string
}

function formatValueM(value: number): string {
    return `$${value.toFixed(2)}M`
}

function RevenueDonutTooltip({
    active,
    payload,
    total,
}: TooltipProps<number, string> & { total: number }) {
    if (!active || !payload?.length) return null
    const entry = payload[0]
    const value = Number(entry.value ?? 0)
    const pct = total > 0 ? Math.round((value / total) * 100) : 0
    return (
        <div
            className="rounded-xl border border-white/20 px-3 py-2 text-[11px] font-bold text-white shadow-lg"
            style={{
                backgroundColor: "rgba(15, 17, 23, 0.85)",
                backdropFilter: "blur(10px)",
            }}
        >
            <p className="uppercase tracking-tight text-white/80">{entry.name}</p>
            <p>
                {formatValueM(value)} · {pct}%
            </p>
        </div>
    )
}

const panelClass =
    "bg-[rgba(255,255,255,0.45)] dark:bg-[rgba(244,246,255,0.4)] backdrop-blur-[15px] border border-white/60 rounded-[14px] p-6 shadow-[0px_2px_15px_0px_rgba(0,0,0,0.06)] hover:shadow-[0px_6px_25px_0px_rgba(108,99,255,0.1)] transition-all duration-300 hover:scale-[1.005] flex flex-col"

export const ReportsRevenueDonutChart = React.memo(function ReportsRevenueDonutChart({
    data,
    range,
    title,
    subtitleSuffix,
    emptyMessage,
    emptyDescription,
    compact = false,
    className,
}: ReportsRevenueDonutChartProps) {
    const periodLabel = formatReportsPeriodLabel(range)
    const hasRevenue = data.some((d) => d.value > 0)
    const total = React.useMemo(
        () => data.reduce((sum, d) => sum + d.value, 0),
        [data],
    )
    const chartHeight = compact ? 140 : 180

    if (!hasRevenue) {
        return (
            <div className={cn(panelClass, className)}>
                <h3 className="text-[13px] font-extrabold text-text font-['Lexend'] mb-0.5">
                    {title}
                </h3>
                <p className="text-[11px] text-gray-700 font-medium mb-4 uppercase tracking-tight">
                    {subtitleSuffix} · {periodLabel}
                </p>
                <NoDataFound
                    message={emptyMessage}
                    description={emptyDescription}
                    size="sm"
                />
            </div>
        )
    }

    return (
        <div className={cn(panelClass, className)}>
            <h3 className="text-[13px] font-extrabold text-text font-['Lexend'] mb-0.5">
                {title}
            </h3>
            <p
                className={cn(
                    "text-[11px] text-gray-700 font-medium uppercase tracking-tight",
                    compact ? "mb-4" : "mb-6",
                )}
            >
                {subtitleSuffix} · {periodLabel}
            </p>

            <div className="flex-1 flex flex-col justify-center px-4 pt-2">
                <div
                    className="relative"
                    style={{ height: chartHeight, minHeight: chartHeight }}
                >
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Pie
                                data={data}
                                dataKey="value"
                                nameKey="name"
                                cx="50%"
                                cy="50%"
                                innerRadius={compact ? 48 : 60}
                                outerRadius={compact ? 64 : 80}
                                paddingAngle={4}
                                stroke="none"
                            >
                                {data.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.color} />
                                ))}
                            </Pie>
                            <Tooltip content={<RevenueDonutTooltip total={total} />} />
                            <Legend
                                verticalAlign="bottom"
                                align="center"
                                iconType="circle"
                                formatter={(value, entry) => {
                                    const v = Number(
                                        (entry as { payload?: { value?: number } }).payload
                                            ?.value ?? 0,
                                    )
                                    const pct =
                                        total > 0 ? Math.round((v / total) * 100) : 0
                                    return `${value} (${formatValueM(v)}, ${pct}%)`
                                }}
                                wrapperStyle={{
                                    fontSize: "10px",
                                    fontWeight: "bold",
                                    paddingTop: compact ? "12px" : "20px",
                                }}
                            />
                        </PieChart>
                    </ResponsiveContainer>
                    <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                        <span
                            className={cn(
                                "font-extrabold text-text leading-none",
                                compact ? "text-[15px]" : "text-[18px]",
                            )}
                        >
                            {formatValueM(total)}
                        </span>
                        <span className="text-[9px] font-bold text-gray-700 uppercase mt-1">
                            Total
                        </span>
                    </div>
                </div>
            </div>
        </div>
    )
})
