"use client"

import * as React from "react"
import {
    ResponsiveContainer,
    BarChart,
    Bar,
    CartesianGrid,
    XAxis,
    YAxis,
    Tooltip,
    Legend,
    LabelList,
} from "recharts"
import type { ServiceSalesByMonthChart } from "./types"
import type { GetReportsParams } from "@/api/rtk/reports-api"
import { NoDataFound } from "@/components/ui/no-data-found"
import { ServiceSalesExportActions } from "./service-sales-export-actions"

interface ServiceSalesByMonthChartProps {
    data?: ServiceSalesByMonthChart | null
    exportQuery?: GetReportsParams
    exportDisabled?: boolean
}

function ServiceSalesCardHeader({
    exportQuery,
    exportDisabled,
}: {
    exportQuery?: GetReportsParams
    exportDisabled?: boolean
}) {
    return (
        <div className="mb-5 flex flex-wrap items-start justify-between gap-3">
            <div>
                <h3 className="text-[13px] font-extrabold text-text font-['Lexend'] mb-0.5">
                    Service Sales by Month
                </h3>
                <p className="text-[11px] text-gray-700 font-medium uppercase tracking-tight">
                    Which service sold most each month · paid transaction count
                </p>
            </div>
            {exportQuery ? (
                <ServiceSalesExportActions
                    query={exportQuery}
                    disabled={exportDisabled}
                />
            ) : null}
        </div>
    )
}

export const ServiceSalesByMonthChartCard = React.memo(
    function ServiceSalesByMonthChartCard({
        data,
        exportQuery,
        exportDisabled = false,
    }: ServiceSalesByMonthChartProps) {
        const series = data?.series ?? []
        const points = data?.data ?? []
        const hasSales = series.length > 0 && points.some((row) =>
            series.some((s) => Number(row[s.key] ?? 0) > 0),
        )

        if (!hasSales) {
            return (
                <div className="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)]">
                    <ServiceSalesCardHeader
                        exportQuery={exportQuery}
                        exportDisabled={exportDisabled}
                    />
                    <NoDataFound
                        message="No service sales yet"
                        description="Paid transactions linked to leads with a service appear here month by month."
                        size="sm"
                    />
                </div>
            )
        }

        return (
            <div className="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]">
                <ServiceSalesCardHeader
                    exportQuery={exportQuery}
                    exportDisabled={exportDisabled}
                />

                <div className="h-[280px]">
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={points} margin={{ top: 8, bottom: 8 }}>
                            <CartesianGrid
                                strokeDasharray="3 3"
                                vertical={false}
                                stroke="#E4E6EF88"
                            />
                            <XAxis
                                dataKey="label"
                                axisLine={false}
                                tickLine={false}
                                tick={{ fontSize: 10, fill: "#6B7280", fontWeight: "bold" }}
                                dy={5}
                            />
                            <YAxis
                                allowDecimals={false}
                                axisLine={false}
                                tickLine={false}
                                tick={{ fontSize: 10, fill: "#6B7280" }}
                            />
                            <Tooltip
                                cursor={{ fill: "#6C63FF08" }}
                                contentStyle={{
                                    borderRadius: "12px",
                                    border: "1px solid rgba(255, 255, 255, 0.2)",
                                    backdropFilter: "blur(10px)",
                                    boxShadow: "0 8px 32px 0 rgba(31, 38, 135, 0.15)",
                                    padding: "10px",
                                    backgroundColor: "rgba(15, 17, 23, 0.85)",
                                    color: "#fff",
                                }}
                                formatter={(value, name) => [
                                    `${value ?? 0} sold`,
                                    String(name),
                                ]}
                            />
                            <Legend
                                verticalAlign="bottom"
                                align="center"
                                iconType="circle"
                                wrapperStyle={{
                                    fontSize: "10px",
                                    fontWeight: "bold",
                                    paddingTop: "16px",
                                }}
                            />
                            {series.map((s, index) => (
                                <Bar
                                    key={s.key}
                                    dataKey={s.key}
                                    name={s.name}
                                    stackId="services"
                                    fill={s.color}
                                    radius={
                                        index === series.length - 1
                                            ? [4, 4, 0, 0]
                                            : [0, 0, 0, 0]
                                    }
                                    barSize={32}
                                >
                                    <LabelList
                                        dataKey={s.key}
                                        position="center"
                                        formatter={(value: number) =>
                                            Number(value) > 0 ? s.name : ""
                                        }
                                        className="fill-white text-[8px] font-extrabold"
                                        style={{
                                            textShadow: "0 1px 2px rgba(0,0,0,0.4)",
                                        }}
                                    />
                                </Bar>
                            ))}
                        </BarChart>
                    </ResponsiveContainer>
                </div>
            </div>
        )
    },
)
