"use client";

import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  LabelList,
  Legend,
  Pie,
  PieChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { formatVnd, formatVndShort } from "@/lib/format";
import { SERIES_COLORS } from "@/lib/chart-colors";

const AXIS = { fontSize: 11, fill: "#6a7a92" };
const GRID = "#e8edf4";

export { SERIES_COLORS };

function TooltipBox({
  active,
  payload,
  label,
  valueFormatter,
}: {
  active?: boolean;
  payload?: { name?: string; value?: number | string; color?: string }[];
  label?: string;
  valueFormatter?: (value: number) => string;
}) {
  if (!active || !payload?.length) return null;
  const format = valueFormatter ?? ((v: number) => formatVnd(v));
  return (
    <div className="rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-xs shadow-sm">
      {label && <div className="mb-1 font-semibold text-ink-700">{label}</div>}
      {payload.map((item, i) => (
        <div key={i} className="tnum flex items-center gap-2 text-ink-500">
          {item.color && (
            <span className="h-2 w-2 rounded-full" style={{ background: item.color }} />
          )}
          <span>{format(Number(item.value ?? 0))}</span>
        </div>
      ))}
    </div>
  );
}

/** Doanh thu theo ngày trong kỳ. */
export function DailyRevenueChart({ data }: { data: { day: string; revenue: number }[] }) {
  const rows = data.map((d) => ({ ...d, label: d.day.slice(8, 10) }));
  return (
    <ResponsiveContainer width="100%" height={220}>
      <AreaChart data={rows} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
        <defs>
          <linearGradient id="revFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#f05a2a" stopOpacity={0.24} />
            <stop offset="100%" stopColor="#f05a2a" stopOpacity={0.02} />
          </linearGradient>
        </defs>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="label" tick={AXIS} axisLine={false} tickLine={false} />
        <YAxis
          tick={AXIS}
          axisLine={false}
          tickLine={false}
          width={54}
          tickFormatter={(v) => formatVndShort(Number(v))}
        />
        <Tooltip content={<TooltipBox />} />
        <Area
          type="monotone"
          dataKey="revenue"
          stroke="#f05a2a"
          strokeWidth={2}
          fill="url(#revFill)"
        />
      </AreaChart>
    </ResponsiveContainer>
  );
}

/** Doanh thu 12 tháng — xu hướng năm. */
export function MonthlyRevenueChart({ data }: { data: { month: string; revenue: number }[] }) {
  const rows = data.map((d) => ({ ...d, label: `T${Number(d.month.slice(5, 7))}` }));
  return (
    <ResponsiveContainer width="100%" height={220}>
      <BarChart data={rows} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="label" tick={AXIS} axisLine={false} tickLine={false} />
        <YAxis
          tick={AXIS}
          axisLine={false}
          tickLine={false}
          width={54}
          tickFormatter={(v) => formatVndShort(Number(v))}
        />
        <Tooltip content={<TooltipBox />} cursor={{ fill: "#f5f7fa" }} />
        <Bar dataKey="revenue" fill="#f05a2a" radius={[4, 4, 0, 0]} maxBarSize={38} />
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Tooltip có tên chuỗi dữ liệu / phần bánh — biểu đồ nhiều chuỗi phải nói rõ số nào là của gì. */
function NamedTooltip({
  active,
  payload,
  label,
  total,
  unit = "money",
}: {
  active?: boolean;
  payload?: { name?: string; value?: number | string; color?: string; payload?: { fill?: string; name?: string } }[];
  label?: string;
  /** Có `total` thì kèm tỷ trọng % trên tổng (biểu đồ tròn). */
  total?: number;
  /** "count": giá trị là số lượng (không phải tiền) — không gắn ký hiệu ₫. */
  unit?: "money" | "count";
}) {
  if (!active || !payload?.length) return null;
  return (
    <div className="rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-xs shadow-sm">
      {label && <div className="mb-1 font-semibold text-ink-700">{label}</div>}
      {payload.map((item, i) => {
        const value = Number(item.value ?? 0);
        return (
          <div key={i} className="tnum flex items-center gap-2 text-ink-500">
            <span className="h-2 w-2 rounded-full" style={{ background: item.color ?? item.payload?.fill }} />
            <span>
              {item.name}: <b className="text-ink-700">{unit === "count" ? value.toLocaleString("vi-VN") : formatVnd(value)}</b>
              {total ? ` (${((value / total) * 100).toFixed(1).replace(".", ",")}%)` : ""}
            </span>
          </div>
        );
      })}
    </div>
  );
}

/**
 * Tỷ trọng đóng góp — bánh + chú giải ngay dưới (tên và % từng phần).
 * Chỉ vẽ tối đa `max` phần lớn nhất, phần còn lại gộp "Khác" để bánh không thành vụn.
 */
export function ShareChart({
  data,
  max = 6,
  height = 200,
  colors,
  unit = "money",
}: {
  data: { name: string; value: number }[];
  max?: number;
  height?: number;
  /** Màu cố định theo tên (để cùng một loại luôn cùng màu ở mọi biểu đồ). */
  colors?: Record<string, string>;
  unit?: "money" | "count";
}) {
  const sorted = [...data].filter((d) => d.value > 0).sort((a, b) => b.value - a.value);
  const head = sorted.slice(0, max);
  const rest = sorted.slice(max).reduce((sum, d) => sum + d.value, 0);
  const rows = rest > 0 ? [...head, { name: "Khác", value: rest }] : head;
  const total = rows.reduce((sum, d) => sum + d.value, 0);

  if (rows.length === 0) return <div className="py-10 text-center text-sm text-ink-400">Chưa có dữ liệu trong kỳ.</div>;
  return (
    <div>
      <ResponsiveContainer width="100%" height={height}>
        <PieChart>
          <Pie data={rows} dataKey="value" nameKey="name" innerRadius={48} outerRadius={78} paddingAngle={2}>
            {rows.map((row, i) => (
              <Cell key={i} fill={colors?.[row.name] ?? SERIES_COLORS[i % SERIES_COLORS.length]} />
            ))}
          </Pie>
          <Tooltip content={<NamedTooltip total={total} unit={unit} />} />
        </PieChart>
      </ResponsiveContainer>
      <ul className="mt-1 grid gap-1 text-xs">
        {rows.map((row, i) => (
          <li key={row.name} className="flex items-center gap-2">
            <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: colors?.[row.name] ?? SERIES_COLORS[i % SERIES_COLORS.length] }} />
            <span className="min-w-0 flex-1 truncate text-ink-600">{row.name}</span>
            <span className="tnum shrink-0 font-semibold text-ink-700">{((row.value / total) * 100).toFixed(1).replace(".", ",")}%</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

/** Xếp hạng ngang — mỗi thanh một đối tượng, nhãn cuối thanh là tỷ trọng %. Dùng cho khu vực / phòng ban / nhân viên / sản phẩm. */
export function RankBarChart({
  data,
  max = 10,
  unit = "money",
  seriesName = "Doanh thu",
  showPercent = true,
}: {
  data: { name: string; value: number }[];
  max?: number;
  unit?: "money" | "count";
  seriesName?: string;
  /** Nhãn cuối thanh: tỷ trọng % trên tổng (mặc định) hoặc chính giá trị. */
  showPercent?: boolean;
}) {
  const total = data.reduce((sum, d) => sum + d.value, 0);
  const rows = [...data]
    .filter((d) => d.value > 0)
    .sort((a, b) => b.value - a.value)
    .slice(0, max)
    .map((d) => ({ ...d, pct: total > 0 ? (d.value / total) * 100 : 0 }));
  if (rows.length === 0) return <div className="py-10 text-center text-sm text-ink-400">Chưa có dữ liệu trong kỳ.</div>;
  return (
    <ResponsiveContainer width="100%" height={Math.max(120, rows.length * 34 + 16)}>
      <BarChart data={rows} layout="vertical" margin={{ top: 4, right: showPercent ? 52 : 80, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} horizontal={false} />
        <XAxis type="number" hide />
        <YAxis type="category" dataKey="name" tick={AXIS} axisLine={false} tickLine={false} width={116} interval={0} />
        <Tooltip content={<NamedTooltip total={showPercent ? total : undefined} unit={unit} />} cursor={{ fill: "#f5f7fa" }} />
        <Bar dataKey="value" name={seriesName} radius={[0, 4, 4, 0]} maxBarSize={20}>
          {rows.map((_, i) => (
            <Cell key={i} fill={SERIES_COLORS[i % SERIES_COLORS.length]} />
          ))}
          <LabelList
            dataKey={showPercent ? "pct" : "value"}
            position="right"
            formatter={(v: unknown) => (showPercent ? `${Number(v).toFixed(1).replace(".", ",")}%` : unit === "count" ? Number(v).toLocaleString("vi-VN") : formatVndShort(Number(v)))}
            style={{ fontSize: 11, fill: "#3b4a63" }}
          />
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Kế hoạch so với thực hiện — hai thanh cạnh nhau cho từng đối tượng. */
export function PlanActualChart({ data }: { data: { name: string; target: number; actual: number }[] }) {
  if (data.length === 0) return <div className="py-10 text-center text-sm text-ink-400">Chưa có dữ liệu trong kỳ.</div>;
  return (
    <ResponsiveContainer width="100%" height={Math.max(160, data.length * 52 + 40)}>
      <BarChart data={data} layout="vertical" margin={{ top: 4, right: 16, bottom: 0, left: 0 }} barCategoryGap="22%">
        <CartesianGrid stroke={GRID} horizontal={false} />
        <XAxis type="number" tick={AXIS} axisLine={false} tickLine={false} tickFormatter={(v) => formatVndShort(Number(v))} />
        <YAxis type="category" dataKey="name" tick={AXIS} axisLine={false} tickLine={false} width={116} interval={0} />
        <Tooltip content={<NamedTooltip />} cursor={{ fill: "#f5f7fa" }} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        <Bar dataKey="target" name="Kế hoạch" fill="#c5cfe0" radius={[0, 4, 4, 0]} maxBarSize={14} />
        <Bar dataKey="actual" name="Thực hiện" fill="#f05a2a" radius={[0, 4, 4, 0]} maxBarSize={14} />
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Doanh số – doanh thu – đã thu theo tháng (cột nhóm). */
export function TrendChart({ data }: { data: { label: string; sales: number; revenue: number; collected: number }[] }) {
  return (
    <ResponsiveContainer width="100%" height={260}>
      <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="label" tick={AXIS} axisLine={false} tickLine={false} />
        <YAxis tick={AXIS} axisLine={false} tickLine={false} width={54} tickFormatter={(v) => formatVndShort(Number(v))} />
        <Tooltip content={<NamedTooltip />} cursor={{ fill: "#f5f7fa" }} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        <Bar dataKey="sales" name="Doanh số" fill="#e8a33d" radius={[3, 3, 0, 0]} maxBarSize={16} />
        <Bar dataKey="revenue" name="Doanh thu" fill="#f05a2a" radius={[3, 3, 0, 0]} maxBarSize={16} />
        <Bar dataKey="collected" name="Đã thu" fill="#214b9a" radius={[3, 3, 0, 0]} maxBarSize={16} />
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Doanh thu từng NVKD kèm đường bình quân — nhìn ra ngay ai trên/dưới định biên. */
export function StaffingChart({ data, average }: { data: { name: string; revenue: number }[]; average: number | null }) {
  if (data.length === 0) return <div className="py-10 text-center text-sm text-ink-400">Chưa có NVKD trong phạm vi này.</div>;
  return (
    <ResponsiveContainer width="100%" height={240}>
      <BarChart data={data} margin={{ top: 16, right: 16, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="name" tick={AXIS} axisLine={false} tickLine={false} interval={0} />
        <YAxis tick={AXIS} axisLine={false} tickLine={false} width={54} tickFormatter={(v) => formatVndShort(Number(v))} />
        <Tooltip content={<NamedTooltip />} cursor={{ fill: "#f5f7fa" }} />
        <Bar dataKey="revenue" name="Doanh thu" fill="#f05a2a" radius={[4, 4, 0, 0]} maxBarSize={40} />
        {average != null && (
          <ReferenceLine y={average} stroke="#214b9a" strokeDasharray="5 4" label={{ value: `Bình quân ${formatVndShort(average)}`, position: "insideTopRight", fontSize: 11, fill: "#214b9a" }} />
        )}
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Số lớp theo thời gian, chồng theo loại lớp. `data` mỗi phần tử: { label, [loại]: số lớp }. */
export function StackedKindChart({ data, kinds, colors }: { data: Record<string, string | number>[]; kinds: string[]; colors: Record<string, string> }) {
  return (
    <ResponsiveContainer width="100%" height={260}>
      <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="label" tick={AXIS} axisLine={false} tickLine={false} interval={0} />
        <YAxis tick={AXIS} axisLine={false} tickLine={false} width={32} allowDecimals={false} />
        <Tooltip content={<NamedTooltip unit="count" />} cursor={{ fill: "#f5f7fa" }} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        {kinds.map((kind) => (
          <Bar key={kind} dataKey={kind} name={kind} stackId="lop" fill={colors[kind]} maxBarSize={44} />
        ))}
      </BarChart>
    </ResponsiveContainer>
  );
}

/** Phân bố đại lý theo hạng A–E. */
export function TierChart({ data }: { data: { tier: string; count: number }[] }) {
  return (
    <ResponsiveContainer width="100%" height={200}>
      <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
        <CartesianGrid stroke={GRID} vertical={false} />
        <XAxis dataKey="tier" tick={AXIS} axisLine={false} tickLine={false} />
        <YAxis tick={AXIS} axisLine={false} tickLine={false} width={32} allowDecimals={false} />
        <Tooltip
          content={<TooltipBox valueFormatter={(v) => `${v} đại lý`} />}
          cursor={{ fill: "#f5f7fa" }}
        />
        <Bar dataKey="count" radius={[4, 4, 0, 0]} maxBarSize={48}>
          {data.map((_, i) => (
            <Cell key={i} fill={SERIES_COLORS[i % SERIES_COLORS.length]} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}
