import React, { useEffect, useRef } from 'react';
import uPlot from 'uplot';
import 'uplot/dist/uPlot.min.css';
import { Database, LineChart, Radio } from 'lucide-react';

interface ChartsDockProps {
  topic: string | null;
  series: { times: number[]; values: number[] } | null;
  fields: { path: string; label: string }[];
  selectedField: string;
  onFieldChange: (path: string) => void;
  source: 'live' | 'db';
  onSourceChange: (source: 'live' | 'db') => void;
}

export const ChartsDock: React.FC<ChartsDockProps> = ({
  topic,
  series,
  fields,
  selectedField,
  onFieldChange,
  source,
  onSourceChange
}) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const plotRef = useRef<uPlot | null>(null);
  const labelRef = useRef<string>('value');
  const effectiveField = selectedField || (fields.length === 1 ? fields[0].path : '');
  const seriesLabel = effectiveField
    ? fields.find((field) => field.path === effectiveField)?.label || 'value'
    : 'value';

  useEffect(() => {
    if (!containerRef.current) {
      return;
    }
    if (!series || !effectiveField) {
      if (plotRef.current) {
        plotRef.current.destroy();
        plotRef.current = null;
      }
      return;
    }

    const opts: uPlot.Options = {
      width: containerRef.current.clientWidth,
      height: 120,
      scales: { x: { time: true } },
      series: [
        {},
        { label: seriesLabel, stroke: '#66d9ef', width: 2 }
      ]
    };

    const data: uPlot.AlignedData = [series.times, series.values];
    if (plotRef.current) {
      if (labelRef.current !== seriesLabel) {
        plotRef.current.destroy();
        plotRef.current = null;
      } else {
        plotRef.current.setData(data);
        return;
      }
    }

    if (!plotRef.current) {
      labelRef.current = seriesLabel;
      plotRef.current = new uPlot(opts, data, containerRef.current);
    }

    return () => {
      plotRef.current?.destroy();
      plotRef.current = null;
    };
  }, [series, effectiveField, seriesLabel]);

  useEffect(() => {
    const resize = () => {
      if (plotRef.current && containerRef.current) {
        plotRef.current.setSize({ width: containerRef.current.clientWidth, height: 120 });
      }
    };
    window.addEventListener('resize', resize);
    return () => window.removeEventListener('resize', resize);
  }, []);

  return (
    <div className="border-t border-[color:var(--border)] bg-[color:var(--bg-panel)] px-4 py-2">
      <div className="flex items-center justify-between text-[10px] opacity-70 mb-2">
        <div className="flex items-center gap-2">
          <LineChart size={12} />
          <span>Graph Dock</span>
          <div className="flex items-center gap-1 ml-2">
            <button
              type="button"
              className={`p-1 rounded border text-[10px] ${source === 'db' ? 'border-[color:var(--accent-green)] text-[color:var(--accent-green)]' : 'border-[color:var(--border)] opacity-60'}`}
              title="Historique (SQLite)"
              onClick={() => onSourceChange('db')}
            >
              <Database size={12} />
            </button>
            <button
              type="button"
              className={`p-1 rounded border text-[10px] ${source === 'live' ? 'border-[color:var(--accent-green)] text-[color:var(--accent-green)]' : 'border-[color:var(--border)] opacity-60'}`}
              title="Flux en direct"
              onClick={() => onSourceChange('live')}
            >
              <Radio size={12} />
            </button>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {fields.length > 0 && (
            <select
              className="bg-[color:var(--bg-main)] border border-[color:var(--border)] rounded px-1 py-0.5 text-[10px]"
              value={selectedField}
              onChange={(event) => onFieldChange(event.target.value)}
            >
              <option value="">Auto</option>
              {fields.map((field) => (
                <option key={field.path} value={field.path}>
                  {field.label}
                </option>
              ))}
            </select>
          )}
          <div className="truncate max-w-[40%]">{topic || 'Aucun topic sélectionné'}</div>
        </div>
      </div>
      {series && effectiveField ? (
        <div ref={containerRef} className="w-full" />
      ) : (
        <div className="text-[10px] italic opacity-60">Aucune série numérique disponible.</div>
      )}
    </div>
  );
};
