import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';

interface Props {
  config: AppConfig;
  splits: LayoutSplits;
  onChange: (splits: LayoutSplits) => void;
}

type Axis = 'x' | 'y';

export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
  const svgRef = useRef<SVGSVGElement>(null);
  
  // State for interaction
  const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); // Proposed new line axis
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); // Normalized 0-1
  const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
  const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);

  // Constants
  const SNAP_THRESHOLD = 0.02; // Reduced threshold slightly for better precision on large grid
  const viewBoxW = 1000;
  const aspectRatio = config.drawer.depth / config.drawer.width;
  const viewBoxH = viewBoxW * aspectRatio;

  // Helpers to calculate cell dimensions
  // IMPORTANT: Dependencies must be correct. dragging updates splits, which updates sortedX/Y
  const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]);
  const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
  
  // Handlers
  const handleMouseMove = (e: React.MouseEvent) => {
    if (!svgRef.current) return;
    const rect = svgRef.current.getBoundingClientRect();
    const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));

    setMousePos({ x: nx, y: ny });

    if (dragging) {
      // Move logic
      // IMPORTANT: Create NEW array references so useMemo in this component and parent components detect changes
      const newSplits = {
          x: [...splits.x],
          y: [...splits.y]
      };
      
      const val = dragging.axis === 'x' ? nx : ny;
      newSplits[dragging.axis][dragging.index] = val;
      
      onChange(newSplits);
      return;
    }

    // Hover logic: Check if near existing lines
    let foundSplit = null;
    
    // Check X splits (Vertical lines)
    splits.x.forEach((val, idx) => {
      if (Math.abs(nx - val) < SNAP_THRESHOLD) foundSplit = { axis: 'x' as Axis, index: idx };
    });

    // Check Y splits (Horizontal lines)
    if (!foundSplit) {
      splits.y.forEach((val, idx) => {
        if (Math.abs(ny - val) < SNAP_THRESHOLD) foundSplit = { axis: 'y' as Axis, index: idx };
      });
    }

    setHoveredSplit(foundSplit);

    // Auto-detect axis for NEW lines if not hovering existing
    // AND if not too close to other lines
    if (!foundSplit) {
        // Check proximity to ALL lines to prevent creating duplicates
        const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
        const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);

        // Also check edges (0 and 1)
        const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
        const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);

        if (closeToX || closeToEdgeX) {
             // Too close to X line or edge, don't allow vertical split here
             // But might allow horizontal?
             // Actually if we are close to an X line, we probably want to select it, which is handled by foundSplit.
             // If foundSplit is null but closeToX is true, it means we are just outside threshold?
             // Let's simplified: if too close to any parallel line, disable creation.
        }

      const distLeft = nx;
      const distRight = 1 - nx;
      const distTop = ny;
      const distBottom = 1 - ny;

      const minXDist = Math.min(distLeft, distRight);
      const minYDist = Math.min(distTop, distBottom);

      // Determine potential axis
      let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
      
      // Validate proximity for that axis
      let valid = true;
      if (potentialAxis === 'x') {
          if (closeToX || closeToEdgeX) valid = false;
      } else {
          if (closeToY || closeToEdgeY) valid = false;
      }

      if (valid) {
          setPhantomAxis(potentialAxis);
      } else {
          setPhantomAxis(null);
      }
    } else {
        setPhantomAxis(null);
    }
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    if (hoveredSplit) {
      // Start Dragging
      if (e.button === 0) { // Left click
          setDragging(hoveredSplit);
      } else if (e.button === 2) { // Right click
          removeSplit(hoveredSplit.axis, hoveredSplit.index);
      }
    } else if (phantomAxis) {
      // Create New Split
      const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
      const newSplits = { ...splits };
      newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
      onChange(newSplits);
      // Immediately start dragging the new line for fine-tuning
      setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
    }
  };

  const handleMouseUp = () => {
    setDragging(null);
  };

  const removeSplit = (axis: Axis, index: number) => {
    const newSplits = { ...splits };
    newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
    onChange(newSplits);
    setHoveredSplit(null);
    setDragging(null);
  };

  return (
    <div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold flex items-center gap-2 text-primary">
          <Grid size={24} /> 2. Редактор макета
        </h2>
        <button 
            onClick={() => onChange({ x: [], y: [] })}
            className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
        >
            <RotateCcw size={14} /> Сбросить сетку
        </button>
      </div>

      <div className="flex flex-col h-full select-none">
        <div className="flex-1 bg-slate-800/30 rounded-lg p-6 flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50">
            
            {/* Instruction Box */}
            <div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[200px] pointer-events-none">
               <div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
                   <MousePointer2 size={14} className="text-primary"/> Инструкция
               </div>
               <ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight">
                   <li><b className="text-blue-400">Клик у края:</b> Новая линия</li>
                   <li><b className="text-orange-400">Перетаскивание:</b> Изменить размер</li>
                   <li><b className="text-red-400">Двойной клик/ПКМ:</b> Удалить</li>
               </ul>
            </div>

            {/* Rulers */}
            <div className="w-full flex justify-between px-8 mb-1 max-w-[900px]">
                <span className="text-xs text-slate-500 font-mono">0</span>
                <span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
            </div>

            <div className="relative flex items-center justify-center w-full h-full">
                 <div className="h-full max-h-[90%] flex flex-col justify-between py-2 mr-2">
                    <span className="text-xs text-slate-500 font-mono">0</span>
                    <span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
                </div>

                {/* Main Interactive SVG */}
                <div 
                    className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
                    style={{
                        width: '100%',
                        maxWidth: '900px',
                        aspectRatio: `${1/aspectRatio}`,
                        cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
                        maxHeight: '75vh'
                    }}
                >   
                   <svg 
                      ref={svgRef}
                      viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} 
                      className="w-full h-full touch-none"
                      onMouseMove={handleMouseMove}
                      onMouseDown={handleMouseDown}
                      onMouseUp={handleMouseUp}
                      onMouseLeave={handleMouseUp}
                      onContextMenu={(e) => e.preventDefault()}
                   >
                      <defs>
                          <pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
                              <path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/>
                          </pattern>
                          <filter id="solid-bg" x="-0.1" y="-0.1" width="1.2" height="1.2">
                             <feFlood floodColor="#1e293b" floodOpacity="0.8"/>
                             <feComposite in="SourceGraphic" operator="over"/>
                          </filter>
                      </defs>
                      <rect width="100%" height="100%" fill="url(#grid)" />

                      {/* --- Cell Dimensions Labels --- */}
                      {sortedX.slice(0, -1).map((x1, i) => {
                          const x2 = sortedX[i + 1];
                          return sortedY.slice(0, -1).map((y1, j) => {
                              const y2 = sortedY[j + 1];
                              const width = (x2 - x1) * config.drawer.width;
                              const depth = (y2 - y1) * config.drawer.depth;
                              const centerX = ((x1 + x2) / 2) * viewBoxW;
                              const centerY = ((y1 + y2) / 2) * viewBoxH;
                              
                              const cellWidthSVG = (x2 - x1) * viewBoxW;
                              const cellHeightSVG = (y2 - y1) * viewBoxH;

                              // Dynamic Font Sizing Logic
                              // Max font size: 36px
                              // Must fit in height: 60% of height max
                              // Must fit in width: approx 25% of width max (assuming ~5 chars)
                              let fontSize = Math.min(36, cellHeightSVG * 0.6);
                              fontSize = Math.min(fontSize, cellWidthSVG * 0.25);

                              // Don't show text if calculated font size is too small to be readable
                              if (fontSize < 10) return null;

                              return (
                                  <text
                                      key={`label-${i}-${j}`}
                                      x={centerX}
                                      y={centerY}
                                      textAnchor="middle"
                                      dominantBaseline="middle"
                                      className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200"
                                      style={{ 
                                          fontSize: `${fontSize}px`, 
                                          textShadow: '1px 1px 3px rgba(0,0,0,0.8)' 
                                      }}
                                  >
                                      {width.toFixed(0)} × {depth.toFixed(0)}
                                  </text>
                              );
                          });
                      })}
                      
                      {/* --- Existing X Lines (Vertical) --- */}
                      {splits.x.map((x, i) => {
                          const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
                          const isDragging = dragging?.axis === 'x' && dragging.index === i;
                          const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
                          const width = isHovered || isDragging ? 8 : 4;

                          return (
                            <g key={`x-${i}`} onDoubleClick={() => removeSplit('x', i)}>
                                {/* Invisible wide hit area */}
                                <line 
                                    x1={x * viewBoxW} y1={0} 
                                    x2={x * viewBoxW} y2={viewBoxH} 
                                    stroke="transparent" strokeWidth="60"
                                    className="cursor-col-resize hover:stroke-white/5"
                                />
                                {/* Visible Line */}
                                <line 
                                    x1={x * viewBoxW} y1={0} 
                                    x2={x * viewBoxW} y2={viewBoxH} 
                                    stroke={color} strokeWidth={width} 
                                    className="transition-all duration-150"
                                />
                                {/* Delete Button if hovered */}
                                {(isHovered || isDragging) && (
                                    <g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}>
                                        <circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
                                        <Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
                                    </g>
                                )}
                            </g>
                          );
                      })}

                      {/* --- Existing Y Lines (Horizontal) --- */}
                      {splits.y.map((y, i) => {
                          const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
                          const isDragging = dragging?.axis === 'y' && dragging.index === i;
                          const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
                          const width = isHovered || isDragging ? 8 : 4;

                          return (
                            <g key={`y-${i}`} onDoubleClick={() => removeSplit('y', i)}>
                                 {/* Invisible wide hit area */}
                                <line 
                                    x1={0} y1={y * viewBoxH} 
                                    x2={viewBoxW} y2={y * viewBoxH} 
                                    stroke="transparent" strokeWidth="60"
                                    className="cursor-row-resize hover:stroke-white/5"
                                />
                                <line 
                                    x1={0} y1={y * viewBoxH} 
                                    x2={viewBoxW} y2={y * viewBoxH} 
                                    stroke={color} strokeWidth={width}
                                    className="transition-all duration-150"
                                />
                                {(isHovered || isDragging) && (
                                    <g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}>
                                        <circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
                                        <Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
                                    </g>
                                )}
                            </g>
                          );
                      })}
                      
                      {/* --- Phantom Line (Preview) --- */}
                      {!hoveredSplit && !dragging && phantomAxis === 'x' && (
                         <g>
                             <line 
                                x1={mousePos.x * viewBoxW} y1="0" 
                                x2={mousePos.x * viewBoxW} y2="100%" 
                                stroke="#3b82f6" 
                                strokeWidth="4" 
                                strokeDasharray="12,8"
                                className="pointer-events-none opacity-60"
                             />
                             <g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}>
                                 <circle r="3" fill="#3b82f6" />
                             </g>
                         </g>
                      )}
                      {!hoveredSplit && !dragging && phantomAxis === 'y' && (
                         <g>
                            <line 
                                x1="0" y1={mousePos.y * viewBoxH} 
                                x2="100%" y2={mousePos.y * viewBoxH} 
                                stroke="#3b82f6" 
                                strokeWidth="4" 
                                strokeDasharray="12,8"
                                className="pointer-events-none opacity-60"
                            />
                            <g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}>
                                 <circle r="3" fill="#3b82f6" />
                             </g>
                         </g>
                      )}
                   </svg>
                </div>
            </div>
        </div>
      </div>
    </div>
  );
};