'use client';

import React, { useMemo } from 'react';
import {
  ComposedChart,
  ResponsiveContainer,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  Line,
  Scatter,
  Bar,
  CartesianGrid,
  ReferenceArea,
} from 'recharts';

import { EvolutionLog } from '@/lib/evolution/history.collector';
import { mapLogsToChartData } from './data-mapper';
import { CustomTooltip } from './CustomTooltip';
import { CustomLegend } from './CustomLegend';
import { CustomDot } from './CustomDot';
import { xAxisTickFormatter, yAxisTickFormatter } from './theme';

// 🧠 Analytics modules
import { predictNextTrend } from '@/lib/awareness/collective/analysis/predict-next';
import { detectStabilityZones } from '@/lib/awareness/collective/analysis/stability-detector';
import { detectConfidenceSurges } from '@/lib/awareness/collective/analysis/confidence-surge';
import { computeInsight, Insight } from '@/lib/awareness/collective/analysis/insight';

interface Props {
  data: EvolutionLog[];
  height?: number;
  onSelect?: (insight: Insight | null) => void;
}

export const EvolutionHistoryChart: React.FC<Props> = ({
  data,
  height = 400,
  onSelect,
}) => {
  /**
   * 🧩 Normalize and deduplicate incoming logs
   * Ensures each timestamp is unique to prevent duplicate tick keys
   */
  const normalizedData = useMemo(() => {
    const normalized = mapLogsToChartData(data)
      .map((d) => ({
        ...d,
        timestamp: new Date(d.timestamp).getTime(),
      }))
      // إزالة التكرارات تمامًا
      .filter(
        (d, i, arr) => i === arr.findIndex((x) => x.timestamp === d.timestamp)
      )
      // ترتيب حسب الزمن للتأكد من ثبات الرسم
      .sort((a, b) => a.timestamp - b.timestamp);
    return normalized;
  }, [data]);

  const prediction = useMemo(() => predictNextTrend(normalizedData), [normalizedData]);
  const stabilityZones = useMemo(
    () => detectStabilityZones(normalizedData),
    [normalizedData]
  );
  const confidenceSurges = useMemo(
    () => detectConfidenceSurges(normalizedData),
    [normalizedData]
  );

  const mergedData = useMemo(
    () => (prediction ? [...normalizedData, prediction] : normalizedData),
    [normalizedData, prediction]
  );

  // 🧠 Handle click → compute insight for specific timestamp
  const handleClick = (payload: any) => {
    if (!onSelect) return;
    const ts =
      payload?.activeLabel ||
      payload?.payload?.timestamp ||
      payload?.chartX ||
      null;
    if (!ts) return;
    const idx = mergedData.findIndex((d) => d.timestamp === ts);
    if (idx >= 0) {
      const insight = computeInsight(mergedData as any, idx, 5);
      onSelect(insight);
    }
  };

  if (!mergedData.length) {
    return (
      <div className="p-3 text-sm opacity-70 text-[hsl(var(--muted-foreground))]">
        No evolution data available.
      </div>
    );
  }

  return (
    <ResponsiveContainer width="100%" height={height}>
      <ComposedChart
        data={mergedData}
        margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
        onClick={handleClick}
      >
        {/* Grid */}
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border)/0.3)" />

        {/* ✅ Safe XAxis with unique tick keys */}
        <XAxis
          dataKey="timestamp"
          type="number"
          scale="time"
          domain={['dataMin', 'dataMax']}
          tickFormatter={xAxisTickFormatter}
          stroke="hsl(var(--foreground)/0.7)"
          interval={0}
          allowDuplicatedCategory={false} // prevents duplicate tick keys
          minTickGap={30}
        />

        {/* Left Y Axis (Trend) */}
        <YAxis
          yAxisId="left"
          dataKey="trendValue"
          domain={[0.5, 3.5]}
          ticks={[1, 2, 3]}
          tickFormatter={yAxisTickFormatter}
          stroke="hsl(var(--foreground)/0.7)"
        />

        {/* Right Y Axis (Change Rate %) */}
        <YAxis
          yAxisId="right"
          orientation="right"
          dataKey="changeRate"
          tickFormatter={(v) => `${v}%`}
          stroke="hsl(var(--foreground)/0.7)"
        />

        <Tooltip content={<CustomTooltip />} />
        <Legend content={<CustomLegend />} />

        {/* Stability zones */}
        {stabilityZones.map((z, i) => (
          <ReferenceArea
            key={`zone-${z.start}-${z.end}-${i}`}
            x1={z.start}
            x2={z.end}
            yAxisId="left"
            fill="rgba(59,130,246,0.08)"
            stroke="none"
          />
        ))}

        {/* Base trend line */}
        <Line
          key="trend-line"
          yAxisId="left"
          type="monotone"
          dataKey="trendValue"
          stroke="hsl(var(--accent))"
          strokeWidth={2}
          dot={false}
          isAnimationActive={false}
          connectNulls
        />

        {/* Prediction line (future trend) */}
        {prediction && (
          <Line
            key={`pred-${prediction.timestamp}`}
            yAxisId="left"
            type="monotone"
            dataKey="trendValue"
            stroke="hsl(var(--primary))"
            strokeDasharray="6 4"
            strokeWidth={2}
            isAnimationActive={false}
            connectNulls
          />
        )}

        {/* Confidence surges */}
        <Scatter
          key="confidence-scatter"
          yAxisId="left"
          dataKey="trendValue"
          shape={<CustomDot />}
        >
          {confidenceSurges.map((s, i) => (
            <circle
              key={`surge-${s.timestamp || i}`}
              cx={0}
              cy={0}
              r={5 + s.confidence * 5}
              fill="hsl(var(--primary))"
              stroke="hsl(var(--border))"
              strokeWidth={0.5}
              opacity={0.9}
            />
          ))}
        </Scatter>

        {/* Change rate bar */}
        <Bar
          key="bar-change-rate"
          yAxisId="right"
          dataKey="changeRate"
          barSize={16}
          fill="hsl(var(--chart-1)/0.4)"
          isAnimationActive={false}
        />
      </ComposedChart>
    </ResponsiveContainer>
  );
};
