'use client';

import React, { useId, useState } from 'react';

function r1(n: number): number {
  return Math.round(n * 10) / 10;
}

function niceMax(v: number): number {
  if (v <= 0) return 1;
  const p = 10 ** Math.floor(Math.log10(v));
  const n = v / p;
  const steps = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];
  const step = steps.find((s) => n <= s) || 10;
  return step * p;
}

function smooth(pts: [number, number][]): string {
  if (pts.length === 0) return '';
  let d = `M${r1(pts[0][0])},${r1(pts[0][1])}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i];
    const p1 = pts[i];
    const p2 = pts[i + 1];
    const p3 = pts[i + 2] || p2;
    const t = 0.18;
    const cp1x = r1(p1[0] + (p2[0] - p0[0]) * t);
    const cp1y = r1(p1[1] + (p2[1] - p0[1]) * t);
    const cp2x = r1(p2[0] - (p3[0] - p1[0]) * t);
    const cp2y = r1(p2[1] - (p3[1] - p1[1]) * t);
    const p2x = r1(p2[0]);
    const p2y = r1(p2[1]);
    d += ` C${cp1x},${cp1y} ${cp2x},${cp2y} ${p2x},${p2y}`;
  }
  return d;
}

export function PrototypeSparkline({ values, color = '#c91c00' }: { values: number[]; color?: string }) {
  const gradId = useId().replace(/:/g, '_');
  const w = 92;
  const h = 34;
  const safeVals = values.length >= 2 ? values : [0, ...values, 0];
  const max = Math.max(...safeVals);
  const min = Math.min(...safeVals);
  const range = max - min || 1;

  const pts: [number, number][] = safeVals.map((v, i) => [i * (w / (safeVals.length - 1)), h - 3 - ((v - min) / range) * (h - 6)]);
  const d = smooth(pts);

  return (
    <svg className="h-[34px] w-[92px] overflow-visible" viewBox={`0 0 ${w} ${h}`} aria-hidden="true">
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity={0.24} />
          <stop offset="100%" stopColor={color} stopOpacity={0} />
        </linearGradient>
      </defs>
      <path d={`${d} L${w},${h} L0,${h} Z`} fill={`url(#${gradId})`} />
      <path d={d} fill="none" stroke={color} strokeWidth={1.8} strokeLinecap="round" />
    </svg>
  );
}

export interface AreaSeries {
  name: string;
  values: number[];
  color: string;
  fill?: boolean;
  dashed?: boolean;
}

export function PrototypeAreaChart({ labels, series, w = 720, h = 240, yFormat = (v) => String(v) }: { labels: string[]; series: AreaSeries[]; w?: number; h?: number; yFormat?: (v: number) => string }) {
  const [hoverIdx, setHoverIdx] = useState<number | null>(null);
  const gradId = useId().replace(/:/g, '_');

  const pad = { l: 52, r: 16, t: 16, b: 32 };
  const iw = w - pad.l - pad.r;
  const ih = h - pad.t - pad.b;

  const allVals = series.flatMap((s) => s.values);
  const max = niceMax(Math.max(...allVals, 1) * 1.05);

  const step = iw / Math.max(labels.length - 1, 1);
  const getX = (i: number) => pad.l + i * step;
  const getY = (v: number) => pad.t + ih - (v / max) * ih;

  const yTicks = [0, 1, 2, 3, 4].map((k) => Number(((max * k) / 4).toFixed(2)));

  return (
    <div className="relative w-full">
      <svg className="w-full h-auto overflow-visible" viewBox={`0 0 ${w} ${h}`} role="img">
        <defs>
          {series.map((s, idx) =>
            s.fill ? (
              <linearGradient key={idx} id={`${gradId}_${idx}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={s.color} stopOpacity={0.24} />
                <stop offset="100%" stopColor={s.color} stopOpacity={0} />
              </linearGradient>
            ) : null,
          )}
        </defs>

        {/* Y Grid & Labels */}
        {yTicks.map((v, k) => {
          const yPos = r1(getY(v));
          return (
            <g key={k}>
              <line x1={pad.l} x2={w - pad.r} y1={yPos} y2={yPos} stroke="currentColor" className="text-slate-200 dark:text-slate-800" strokeWidth={1} />
              <text x={pad.l - 12} y={yPos + 4} textAnchor="end" className="text-[11px] tabular-nums font-medium fill-slate-400 dark:fill-slate-500">
                {yFormat(v)}
              </text>
            </g>
          );
        })}

        {/* X Labels */}
        {labels.map((lbl, i) => (
          <text key={i} x={r1(getX(i))} y={h - 10} textAnchor="middle" className="text-[11px] font-medium fill-slate-400 dark:fill-slate-500">
            {lbl}
          </text>
        ))}

        {/* Series Paths */}
        {series.map((s, idx) => {
          const pts: [number, number][] = s.values.map((v, i) => [getX(i), getY(v)]);
          const d = smooth(pts);
          return (
            <g key={idx}>
              {s.fill ? <path d={`${d} L${r1(getX(pts.length - 1))},${pad.t + ih} L${pad.l},${pad.t + ih} Z`} fill={`url(#${gradId}_${idx})`} /> : null}
              <path d={d} fill="none" stroke={s.color} strokeWidth={s.dashed ? 1.8 : 2.5} strokeDasharray={s.dashed ? '5 5' : undefined} strokeLinecap="round" />
            </g>
          );
        })}

        {/* Interactive Hover Guides & Dots */}
        {labels.map((_, i) => {
          const xPos = r1(getX(i));
          const isHover = hoverIdx === i;
          return (
            <g key={i} className="cursor-pointer" onMouseEnter={() => setHoverIdx(i)} onMouseLeave={() => setHoverIdx(null)}>
              {isHover ? <line x1={xPos} x2={xPos} y1={pad.t} y2={pad.t + ih} stroke="#94a3b8" strokeWidth={1} strokeDasharray="3 3" /> : null}
              {series.map((s, j) => {
                const val = s.values[i];
                const yPos = r1(getY(val));
                return isHover ? <circle key={j} cx={xPos} cy={yPos} r={5} fill="#fff" stroke={s.color} strokeWidth={2.5} /> : null;
              })}
              <rect x={r1(xPos - step / 2)} y={pad.t} width={r1(step)} height={ih} fill="transparent" />
            </g>
          );
        })}
      </svg>

      {/* Floating Tooltip */}
      {hoverIdx !== null ? (
        <div
          className="pointer-events-none absolute top-4 z-20 rounded-md border border-slate-200 bg-white/95 px-3 py-1.5 text-xs shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/95"
          style={{
            left: `${Math.min(Math.max(getX(hoverIdx) - 40, 10), w - 120)}px`,
          }}
        >
          <div className="font-semibold text-slate-900 dark:text-slate-100">{labels[hoverIdx]}</div>
          {series.map((s, idx) => (
            <div key={idx} className="flex items-center gap-1.5 text-[11px] text-slate-600 dark:text-slate-300">
              <span className="h-2 w-2 rounded-full" style={{ backgroundColor: s.color }} />
              <span>{s.name}:</span>
              <span className="font-semibold tabular-nums">{yFormat(s.values[hoverIdx])}</span>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
}

export interface BarSeries {
  name: string;
  values: number[];
  color: string;
}

export function PrototypeBarChart({ labels, series, w = 720, h = 240, yFormat = (v) => String(v) }: { labels: string[]; series: BarSeries[]; w?: number; h?: number; yFormat?: (v: number) => string }) {
  const pad = { l: 52, r: 16, t: 16, b: 32 };
  const iw = w - pad.l - pad.r;
  const ih = h - pad.t - pad.b;

  const allVals = series.flatMap((s) => s.values);
  const max = niceMax(Math.max(...allVals, 1) * 1.05);

  const getY = (v: number) => pad.t + ih - (v / max) * ih;
  const band = iw / Math.max(labels.length, 1);
  const gw = Math.min(band * 0.65, 48);
  const bw = gw / series.length;

  const yTicks = [0, 1, 2, 3, 4].map((k) => Number(((max * k) / 4).toFixed(2)));

  return (
    <div className="w-full">
      <svg className="w-full h-auto overflow-visible" viewBox={`0 0 ${w} ${h}`} role="img">
        {/* Y Grid */}
        {yTicks.map((v, k) => {
          const yPos = r1(getY(v));
          return (
            <g key={k}>
              <line x1={pad.l} x2={w - pad.r} y1={yPos} y2={yPos} stroke="currentColor" className="text-slate-200 dark:text-slate-800" strokeWidth={1} />
              <text x={pad.l - 12} y={yPos + 4} textAnchor="end" className="text-[11px] tabular-nums font-medium fill-slate-400 dark:fill-slate-500">
                {yFormat(v)}
              </text>
            </g>
          );
        })}

        {/* Bars and X Labels */}
        {labels.map((lbl, i) => {
          const gx = pad.l + i * band + (band - gw) / 2;
          return (
            <g key={i}>
              {series.map((s, j) => {
                const val = s.values[i];
                const yPos = r1(getY(val));
                const barH = Math.max(2, ih - (yPos - pad.t));
                return (
                  <rect
                    key={j}
                    x={r1(gx + j * bw + 1)}
                    y={yPos}
                    width={r1(Math.max(bw - 2, 3))}
                    height={r1(barH)}
                    rx={3}
                    fill={s.color}
                    style={{
                      animationDelay: `${(i * series.length + j) * 45}ms`,
                    }}
                    className="anim-grow-y transition-opacity duration-150 hover:opacity-80 cursor-pointer"
                  >
                    <title>{`${lbl} · ${s.name}: ${yFormat(val)}`}</title>
                  </rect>
                );
              })}
              <text x={r1(pad.l + i * band + band / 2)} y={h - 10} textAnchor="middle" className="text-[11px] font-medium fill-slate-400 dark:fill-slate-500">
                <title>{lbl}</title>
                {lbl.length > 15 ? `${lbl.slice(0, 13)}…` : lbl}
              </text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

export function PrototypeDonutChart({ segments, centerValue, centerLabel, size = 168, thick, thickness }: { segments: { label: string; value: number; color: string }[]; centerValue: string; centerLabel: string; size?: number; thick?: number; thickness?: number }) {
  const barThickness = thick ?? thickness ?? 20;
  const r = (size - barThickness) / 2 - 3;
  const C = 2 * Math.PI * r;
  const total = segments.reduce((s, seg) => s + seg.value, 0) || 1;

  const segElements = segments.map((s, i) => {
    const prevSum = segments.slice(0, i).reduce((sum, item) => sum + item.value, 0);
    const len = (s.value / total) * C;
    const gap = segments.length > 1 ? Math.min(3, len * 0.3) : 0;
    const dashVal = Math.max(len - gap, 0.1);
    const offset = -(prevSum / total) * C;

    return (
      <circle key={i} cx={size / 2} cy={size / 2} r={r1(r)} fill="none" stroke={s.color} strokeWidth={barThickness} strokeDasharray={`${r1(dashVal)} ${r1(C)}`} strokeDashoffset={r1(offset)} className="transition-all duration-200 hover:stroke-[24px]">
        <title>{`${s.label}: ${s.value} (${Math.round((s.value / total) * 100)}%)`}</title>
      </circle>
    );
  });

  return (
    <svg className="shrink-0" style={{ width: size, height: size }} viewBox={`0 0 ${size} ${size}`}>
      <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>
        <circle cx={size / 2} cy={size / 2} r={r1(r)} fill="none" stroke="currentColor" className="text-slate-100 dark:text-slate-800" strokeWidth={barThickness} />
        {segElements}
      </g>
      <text x="50%" y={size / 2 + 3} textAnchor="middle" className="fill-slate-900 text-[22px] font-bold tracking-tight tabular-nums dark:fill-white">
        {centerValue}
      </text>
      <text x="50%" y={size / 2 + 20} textAnchor="middle" className="fill-slate-400 text-[11.5px] font-medium uppercase tracking-wider dark:fill-slate-500">
        {centerLabel}
      </text>
    </svg>
  );
}

export function PrototypeDealPulse({ days, stage }: { days: number; stage?: string }) {
  const isWon = stage === 'WON' || stage === 'won' || stage === 'CLOSED_WON';
  const isLost = stage === 'LOST' || stage === 'lost' || stage === 'CLOSED_LOST';
  const isStalled = days > 30;
  const isSlow = days > 14;

  const barColor = isWon ? 'bg-emerald-500' : isLost || isStalled ? 'bg-rose-600' : isSlow ? 'bg-amber-500' : 'bg-[#c91c00]';

  const labelColor = isWon ? 'text-emerald-600' : isLost || isStalled ? 'text-rose-600' : isSlow ? 'text-amber-600' : 'text-slate-500';

  const label = isWon ? 'Won' : isLost ? 'Lost' : `${days} ${days === 1 ? 'day' : 'days'} in stage${isStalled ? ', stalled' : isSlow ? ', slowing' : ''}`;

  return (
    <div className="flex flex-col items-end gap-1">
      <div className="grid grid-cols-5 gap-0.5 w-16 h-1">
        {[0, 1, 2, 3, 4].map((i) => (
          <i key={i} className={`h-full rounded-sm transition-colors ${i <= (isStalled ? 2 : isSlow ? 3 : 4) ? barColor : 'bg-slate-200 dark:bg-slate-700'}`} />
        ))}
      </div>
      <span className={`text-[11px] font-medium tabular-nums ${labelColor}`}>{label}</span>
    </div>
  );
}

export function PrototypeFunnel({ steps, color }: { steps: { label: string; count: number }[]; color?: string }) {
  const primary = color || 'var(--tcx-primary, #0071e3)';
  const [hoveredIdx, setHoveredIdx] = useState<number | null>(null);

  return (
    <div className="flex flex-col items-center gap-2.5 py-1 w-full">
      {steps.map((step, i) => {
        const widthPct = Math.max(35, 100 - i * 15);
        const bg = `color-mix(in srgb, ${primary} ${100 - i * 14}%, #5856d6)`;
        const prevCount = i > 0 ? steps[i - 1].count : 0;
        const prevPct = i > 0 && prevCount > 0 ? Math.round((step.count / prevCount) * 100) : 100;

        return (
          <div
            key={step.label}
            style={{
              width: `${widthPct}%`,
              background: bg,
              animationDelay: `${i * 70}ms`,
            }}
            onMouseEnter={() => setHoveredIdx(i)}
            onMouseLeave={() => setHoveredIdx(null)}
            className="group relative flex h-11 items-center justify-center rounded-xl font-semibold text-white text-[13px] shadow-sm transition-transform duration-200 hover:scale-[1.02] cursor-pointer anim-grow-center"
          >
            <span className="tabular-nums">
              {step.label}: {step.count.toLocaleString('en-IN')}
            </span>
            {hoveredIdx === i && i > 0 && <span className="absolute -top-7 z-10 whitespace-nowrap rounded-md bg-slate-900/90 px-2 py-0.5 text-[11px] font-normal text-white shadow-lg backdrop-blur-xs">{prevPct}% of previous step</span>}
          </div>
        );
      })}
    </div>
  );
}
