/**
 * ChartDrawingToolsPanel Component
 * Drawing tools for technical analysis on charts
 * OQI-003: Trading y Charts
 */

import React, { useState, useMemo } from 'react';
import {
  Pencil,
  TrendingUp,
  Minus,
  Square,
  Circle,
  Type,
  Trash2,
  RotateCcw,
  Layers,
  Eye,
  EyeOff,
  Lock,
  Unlock,
  Palette,
  ChevronDown,
  ChevronUp,
  Copy,
  ArrowUpRight,
  Triangle,
  Hash,
} from 'lucide-react';

export type DrawingTool =
  | 'trendline'
  | 'horizontal'
  | 'vertical'
  | 'rectangle'
  | 'circle'
  | 'fibonacci'
  | 'text'
  | 'arrow'
  | 'channel'
  | 'pitchfork';

export interface Drawing {
  id: string;
  tool: DrawingTool;
  color: string;
  lineWidth: number;
  visible: boolean;
  locked: boolean;
  label?: string;
  points: { x: number; y: number; price?: number; time?: string }[];
  createdAt: string;
}

interface ChartDrawingToolsPanelProps {
  drawings?: Drawing[];
  activeTool?: DrawingTool | null;
  onToolSelect?: (tool: DrawingTool | null) => void;
  onDrawingAdd?: (drawing: Drawing) => void;
  onDrawingUpdate?: (drawing: Drawing) => void;
  onDrawingRemove?: (drawingId: string) => void;
  onDrawingsVisibilityToggle?: (visible: boolean) => void;
  onClearAll?: () => void;
  onUndo?: () => void;
  compact?: boolean;
}

const DRAWING_TOOLS: { tool: DrawingTool; label: string; icon: React.ReactNode; description: string }[] = [
  { tool: 'trendline', label: 'Trendline', icon: <TrendingUp className="w-4 h-4" />, description: 'Draw trend lines' },
  { tool: 'horizontal', label: 'Horizontal', icon: <Minus className="w-4 h-4" />, description: 'Support/resistance levels' },
  { tool: 'vertical', label: 'Vertical', icon: <Minus className="w-4 h-4 rotate-90" />, description: 'Mark time points' },
  { tool: 'rectangle', label: 'Rectangle', icon: <Square className="w-4 h-4" />, description: 'Price zones' },
  { tool: 'circle', label: 'Circle', icon: <Circle className="w-4 h-4" />, description: 'Highlight areas' },
  { tool: 'fibonacci', label: 'Fibonacci', icon: <Hash className="w-4 h-4" />, description: 'Fib retracement' },
  { tool: 'text', label: 'Text', icon: <Type className="w-4 h-4" />, description: 'Add annotations' },
  { tool: 'arrow', label: 'Arrow', icon: <ArrowUpRight className="w-4 h-4" />, description: 'Direction markers' },
  { tool: 'channel', label: 'Channel', icon: <Layers className="w-4 h-4" />, description: 'Price channels' },
  { tool: 'pitchfork', label: 'Pitchfork', icon: <Triangle className="w-4 h-4" />, description: 'Andrews pitchfork' },
];

const PRESET_COLORS = [
  '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
  '#EC4899', '#06B6D4', '#84CC16', '#F97316', '#FFFFFF',
];

const ChartDrawingToolsPanel: React.FC<ChartDrawingToolsPanelProps> = ({
  drawings = [],
  activeTool = null,
  onToolSelect,
  onDrawingAdd,
  onDrawingUpdate,
  onDrawingRemove,
  onDrawingsVisibilityToggle,
  onClearAll,
  onUndo,
  compact = false,
}) => {
  const [selectedColor, setSelectedColor] = useState('#3B82F6');
  const [lineWidth, setLineWidth] = useState(2);
  const [showDrawingsList, setShowDrawingsList] = useState(false);
  const [expandedDrawingId, setExpandedDrawingId] = useState<string | null>(null);
  const [allVisible, setAllVisible] = useState(true);

  const visibleCount = useMemo(() => drawings.filter(d => d.visible).length, [drawings]);

  const handleToolClick = (tool: DrawingTool) => {
    if (activeTool === tool) {
      onToolSelect?.(null);
    } else {
      onToolSelect?.(tool);
    }
  };

  const handleToggleVisibility = (drawing: Drawing) => {
    onDrawingUpdate?.({ ...drawing, visible: !drawing.visible });
  };

  const handleToggleLock = (drawing: Drawing) => {
    onDrawingUpdate?.({ ...drawing, locked: !drawing.locked });
  };

  const handleUpdateColor = (drawing: Drawing, color: string) => {
    onDrawingUpdate?.({ ...drawing, color });
  };

  const handleDuplicateDrawing = (drawing: Drawing) => {
    const newDrawing: Drawing = {
      ...drawing,
      id: `draw_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      createdAt: new Date().toISOString(),
      locked: false,
      points: drawing.points.map(p => ({ ...p, y: p.y + 10 })),
    };
    onDrawingAdd?.(newDrawing);
  };

  const handleToggleAllVisibility = () => {
    const newVisible = !allVisible;
    setAllVisible(newVisible);
    onDrawingsVisibilityToggle?.(newVisible);
  };

  const getToolLabel = (tool: DrawingTool) => {
    return DRAWING_TOOLS.find(t => t.tool === tool)?.label || tool;
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <Pencil className="w-5 h-5 text-blue-400" />
          <div>
            <h3 className="font-semibold text-white">Drawing Tools</h3>
            <p className="text-xs text-gray-500">{visibleCount} of {drawings.length} visible</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={onUndo}
            disabled={drawings.length === 0}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            title="Undo"
          >
            <RotateCcw className="w-4 h-4" />
          </button>
          <button
            onClick={handleToggleAllVisibility}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            title={allVisible ? 'Hide All' : 'Show All'}
          >
            {allVisible ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
          </button>
          <button
            onClick={onClearAll}
            disabled={drawings.length === 0}
            className="p-2 text-gray-400 hover:text-red-400 hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            title="Clear All"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Tool Grid */}
      <div className="grid grid-cols-5 gap-2 mb-4">
        {DRAWING_TOOLS.map(({ tool, label, icon, description }) => (
          <button
            key={tool}
            onClick={() => handleToolClick(tool)}
            className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all ${
              activeTool === tool
                ? 'bg-blue-600 text-white ring-2 ring-blue-400'
                : 'bg-gray-900/50 text-gray-400 hover:bg-gray-700 hover:text-white'
            }`}
            title={description}
          >
            {icon}
            <span className="text-[10px]">{label}</span>
          </button>
        ))}
      </div>

      {/* Active Tool Options */}
      {activeTool && (
        <div className="p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg mb-4">
          <div className="flex items-center justify-between mb-3">
            <span className="text-sm text-blue-400 font-medium">
              {getToolLabel(activeTool)} Selected
            </span>
            <button
              onClick={() => onToolSelect?.(null)}
              className="text-xs text-blue-400 hover:text-blue-300"
            >
              Cancel
            </button>
          </div>

          <div className="flex items-center gap-4">
            {/* Color Picker */}
            <div>
              <label className="block text-xs text-gray-500 mb-1">Color</label>
              <div className="flex gap-1">
                {PRESET_COLORS.slice(0, 5).map((color) => (
                  <button
                    key={color}
                    onClick={() => setSelectedColor(color)}
                    className={`w-6 h-6 rounded-full border-2 transition-all ${
                      selectedColor === color ? 'border-white scale-110' : 'border-transparent'
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            {/* Line Width */}
            <div>
              <label className="block text-xs text-gray-500 mb-1">Width</label>
              <div className="flex gap-1">
                {[1, 2, 3, 4].map((width) => (
                  <button
                    key={width}
                    onClick={() => setLineWidth(width)}
                    className={`w-7 h-6 rounded text-xs font-medium ${
                      lineWidth === width
                        ? 'bg-blue-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    {width}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <p className="text-xs text-gray-500 mt-2">
            Click on the chart to start drawing
          </p>
        </div>
      )}

      {/* Drawings List */}
      <div>
        <button
          onClick={() => setShowDrawingsList(!showDrawingsList)}
          className="flex items-center justify-between w-full p-2 bg-gray-900/50 rounded-lg hover:bg-gray-800 transition-colors"
        >
          <div className="flex items-center gap-2">
            <Layers className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-white">Drawings ({drawings.length})</span>
          </div>
          {showDrawingsList ? (
            <ChevronUp className="w-4 h-4 text-gray-500" />
          ) : (
            <ChevronDown className="w-4 h-4 text-gray-500" />
          )}
        </button>

        {showDrawingsList && (
          <div className="mt-2 space-y-1 max-h-[200px] overflow-y-auto">
            {drawings.length === 0 ? (
              <div className="text-center py-4">
                <p className="text-gray-500 text-xs">No drawings yet</p>
              </div>
            ) : (
              drawings.map((drawing) => {
                const toolDef = DRAWING_TOOLS.find(t => t.tool === drawing.tool);
                const isExpanded = expandedDrawingId === drawing.id;

                return (
                  <div
                    key={drawing.id}
                    className={`bg-gray-900/50 rounded-lg border transition-all ${
                      drawing.visible ? 'border-gray-700' : 'border-gray-800 opacity-60'
                    }`}
                  >
                    <div
                      onClick={() => setExpandedDrawingId(isExpanded ? null : drawing.id)}
                      className="flex items-center justify-between p-2 cursor-pointer hover:bg-gray-800/50"
                    >
                      <div className="flex items-center gap-2">
                        <div
                          className="w-3 h-3 rounded-full"
                          style={{ backgroundColor: drawing.color }}
                        />
                        <div className="p-1 bg-gray-800 rounded" style={{ color: drawing.color }}>
                          {toolDef?.icon}
                        </div>
                        <div>
                          <span className="text-sm text-white">{toolDef?.label}</span>
                          {drawing.label && (
                            <span className="text-xs text-gray-500 ml-2">{drawing.label}</span>
                          )}
                        </div>
                      </div>

                      <div className="flex items-center gap-1">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleToggleVisibility(drawing);
                          }}
                          className="p-1 text-gray-500 hover:text-white"
                        >
                          {drawing.visible ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleToggleLock(drawing);
                          }}
                          className="p-1 text-gray-500 hover:text-white"
                        >
                          {drawing.locked ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3" />}
                        </button>
                        {isExpanded ? (
                          <ChevronUp className="w-3 h-3 text-gray-500" />
                        ) : (
                          <ChevronDown className="w-3 h-3 text-gray-500" />
                        )}
                      </div>
                    </div>

                    {isExpanded && (
                      <div className="px-2 pb-2 pt-1 border-t border-gray-800">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-xs text-gray-500">Color:</span>
                          <div className="flex gap-1">
                            {PRESET_COLORS.slice(0, 5).map((color) => (
                              <button
                                key={color}
                                onClick={() => handleUpdateColor(drawing, color)}
                                className={`w-4 h-4 rounded-full border transition-all ${
                                  drawing.color === color ? 'border-white' : 'border-transparent'
                                }`}
                                style={{ backgroundColor: color }}
                              />
                            ))}
                          </div>
                        </div>

                        <div className="flex items-center justify-between text-xs">
                          <span className="text-gray-500">
                            Created: {formatTime(drawing.createdAt)}
                          </span>
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleDuplicateDrawing(drawing)}
                              className="p-1 text-gray-400 hover:text-white"
                              title="Duplicate"
                            >
                              <Copy className="w-3 h-3" />
                            </button>
                            <button
                              onClick={() => onDrawingRemove?.(drawing.id)}
                              disabled={drawing.locked}
                              className="p-1 text-gray-400 hover:text-red-400 disabled:opacity-50"
                              title="Delete"
                            >
                              <Trash2 className="w-3 h-3" />
                            </button>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>
        )}
      </div>

      {/* Quick Tips */}
      {!compact && (
        <div className="mt-4 pt-4 border-t border-gray-700">
          <div className="text-xs text-gray-500">
            <p className="mb-1"><strong>Tips:</strong></p>
            <ul className="space-y-0.5 text-gray-600">
              <li>• Click and drag to draw</li>
              <li>• Double-click to finish</li>
              <li>• Hold Shift for straight lines</li>
            </ul>
          </div>
        </div>
      )}
    </div>
  );
};

export default ChartDrawingToolsPanel;
