'use client';

import { useState, useRef, useEffect } from 'react';
import { 
  Pencil, 
  Eraser, 
  RotateCcw, 
  Download, 
  Circle,
  Square,
  Minus,
  Type,
  Palette
} from 'lucide-react';

interface Point {
  x: number;
  y: number;
}

interface DrawElement {
  type: 'line' | 'circle' | 'rectangle' | 'text' | 'freehand';
  points: Point[];
  color: string;
  strokeWidth: number;
  text?: string;
}

interface EyeDiagramProps {
  eye: 'OD' | 'OS';
  type: 'anterior' | 'fundus';
  initialData?: string;
  onChange?: (data: string) => void;
  readOnly?: boolean;
}

const COLORS = [
  '#000000', '#EF4444', '#F97316', '#EAB308', '#22C55E', 
  '#3B82F6', '#8B5CF6', '#EC4899', '#6B7280'
];

const STROKE_WIDTHS = [1, 2, 3, 5, 8];

export default function EyeDiagram({ eye, type, initialData, onChange, readOnly = false }: EyeDiagramProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [tool, setTool] = useState<'pencil' | 'eraser' | 'circle' | 'rectangle' | 'line' | 'text'>('pencil');
  const [color, setColor] = useState('#EF4444');
  const [strokeWidth, setStrokeWidth] = useState(2);
  const [elements, setElements] = useState<DrawElement[]>([]);
  const [currentElement, setCurrentElement] = useState<DrawElement | null>(null);
  const [history, setHistory] = useState<DrawElement[][]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);

  const anteriorSegmentTemplate = `
    <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
      <!-- Outer cornea -->
      <circle cx="100" cy="100" r="85" fill="none" stroke="#94A3B8" stroke-width="2"/>
      <!-- Limbus -->
      <circle cx="100" cy="100" r="75" fill="none" stroke="#94A3B8" stroke-width="1"/>
      <!-- Iris -->
      <circle cx="100" cy="100" r="55" fill="none" stroke="#64748B" stroke-width="1.5"/>
      <!-- Pupil -->
      <circle cx="100" cy="100" r="20" fill="#1E293B" stroke="#1E293B" stroke-width="1"/>
      <!-- Corneal reflex -->
      <circle cx="90" cy="90" r="5" fill="white" opacity="0.7"/>
      <!-- Clock hours -->
      <text x="100" y="10" text-anchor="middle" fill="#94A3B8" font-size="10">12</text>
      <text x="190" y="105" text-anchor="middle" fill="#94A3B8" font-size="10">3</text>
      <text x="100" y="198" text-anchor="middle" fill="#94A3B8" font-size="10">6</text>
      <text x="10" y="105" text-anchor="middle" fill="#94A3B8" font-size="10">9</text>
    </svg>
  `;

  const fundusTemplate = `
    <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
      <!-- Retina background -->
      <circle cx="100" cy="100" r="90" fill="#FDE68A" opacity="0.3" stroke="#F59E0B" stroke-width="1"/>
      <!-- Optic disc -->
      <ellipse cx="${eye === 'OD' ? '140' : '60'}" cy="100" rx="15" ry="18" fill="#FEF3C7" stroke="#F59E0B" stroke-width="1.5"/>
      <!-- Cup -->
      <ellipse cx="${eye === 'OD' ? '140' : '60'}" cy="100" rx="6" ry="7" fill="#FDE68A" stroke="#F59E0B" stroke-width="0.5"/>
      <!-- Macula -->
      <circle cx="${eye === 'OD' ? '70' : '130'}" cy="100" r="12" fill="none" stroke="#DC2626" stroke-width="0.5" stroke-dasharray="2"/>
      <!-- Fovea -->
      <circle cx="${eye === 'OD' ? '70' : '130'}" cy="100" r="3" fill="#991B1B"/>
      <!-- Major vessels -->
      <path d="M ${eye === 'OD' ? '125' : '75'} 82 Q ${eye === 'OD' ? '100' : '100'} 50, ${eye === 'OD' ? '60' : '140'} 30" fill="none" stroke="#DC2626" stroke-width="1.5"/>
      <path d="M ${eye === 'OD' ? '125' : '75'} 118 Q ${eye === 'OD' ? '100' : '100'} 150, ${eye === 'OD' ? '60' : '140'} 170" fill="none" stroke="#DC2626" stroke-width="1.5"/>
      <path d="M ${eye === 'OD' ? '125' : '75'} 82 Q ${eye === 'OD' ? '100' : '100'} 50, ${eye === 'OD' ? '60' : '140'} 30" fill="none" stroke="#3B82F6" stroke-width="1" transform="translate(5,5)"/>
      <path d="M ${eye === 'OD' ? '125' : '75'} 118 Q ${eye === 'OD' ? '100' : '100'} 150, ${eye === 'OD' ? '60' : '140'} 170" fill="none" stroke="#3B82F6" stroke-width="1" transform="translate(5,5)"/>
      <!-- Label -->
      <text x="100" y="195" text-anchor="middle" fill="#64748B" font-size="8">${eye} Fundus</text>
    </svg>
  `;

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    const img = new Image();
    const svgBlob = new Blob([type === 'anterior' ? anteriorSegmentTemplate : fundusTemplate], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(svgBlob);
    
    img.onload = () => {
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      URL.revokeObjectURL(url);
      
      elements.forEach(element => {
        drawElement(ctx, element);
      });
      
      if (currentElement) {
        drawElement(ctx, currentElement);
      }
    };
    
    img.src = url;
  }, [elements, currentElement, type, eye]);

  const drawElement = (ctx: CanvasRenderingContext2D, element: DrawElement) => {
    ctx.strokeStyle = element.color;
    ctx.lineWidth = element.strokeWidth;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    switch (element.type) {
      case 'freehand':
      case 'line':
        if (element.points.length < 2) return;
        ctx.beginPath();
        ctx.moveTo(element.points[0].x, element.points[0].y);
        for (let i = 1; i < element.points.length; i++) {
          ctx.lineTo(element.points[i].x, element.points[i].y);
        }
        ctx.stroke();
        break;
      case 'circle':
        if (element.points.length < 2) return;
        const radius = Math.sqrt(
          Math.pow(element.points[1].x - element.points[0].x, 2) +
          Math.pow(element.points[1].y - element.points[0].y, 2)
        );
        ctx.beginPath();
        ctx.arc(element.points[0].x, element.points[0].y, radius, 0, Math.PI * 2);
        ctx.stroke();
        break;
      case 'rectangle':
        if (element.points.length < 2) return;
        ctx.beginPath();
        ctx.rect(
          element.points[0].x,
          element.points[0].y,
          element.points[1].x - element.points[0].x,
          element.points[1].y - element.points[0].y
        );
        ctx.stroke();
        break;
      case 'text':
        if (!element.text) return;
        ctx.font = `${element.strokeWidth * 6}px sans-serif`;
        ctx.fillStyle = element.color;
        ctx.fillText(element.text, element.points[0].x, element.points[0].y);
        break;
    }
  };

  const getMousePos = (e: React.MouseEvent<HTMLCanvasElement>): Point => {
    const canvas = canvasRef.current;
    if (!canvas) return { x: 0, y: 0 };
    const rect = canvas.getBoundingClientRect();
    return {
      x: (e.clientX - rect.left) * (canvas.width / rect.width),
      y: (e.clientY - rect.top) * (canvas.height / rect.height)
    };
  };

  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (readOnly) return;
    setIsDrawing(true);
    const pos = getMousePos(e);

    if (tool === 'text') {
      const text = prompt('Enter text:');
      if (text) {
        const newElement: DrawElement = {
          type: 'text',
          points: [pos],
          color,
          strokeWidth,
          text
        };
        const newElements = [...elements, newElement];
        setElements(newElements);
        saveHistory(newElements);
      }
      return;
    }

    const newElement: DrawElement = {
      type: tool === 'pencil' || tool === 'eraser' ? 'freehand' : tool,
      points: [pos],
      color: tool === 'eraser' ? '#FFFFFF' : color,
      strokeWidth: tool === 'eraser' ? strokeWidth * 3 : strokeWidth
    };
    setCurrentElement(newElement);
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDrawing || !currentElement || readOnly) return;
    const pos = getMousePos(e);

    if (currentElement.type === 'freehand') {
      setCurrentElement({
        ...currentElement,
        points: [...currentElement.points, pos]
      });
    } else {
      setCurrentElement({
        ...currentElement,
        points: [currentElement.points[0], pos]
      });
    }
  };

  const handleMouseUp = () => {
    if (!isDrawing || !currentElement) return;
    setIsDrawing(false);
    
    const newElements = [...elements, currentElement];
    setElements(newElements);
    setCurrentElement(null);
    saveHistory(newElements);
    
    if (onChange) {
      onChange(JSON.stringify(newElements));
    }
  };

  const saveHistory = (newElements: DrawElement[]) => {
    const newHistory = history.slice(0, historyIndex + 1);
    newHistory.push(newElements);
    setHistory(newHistory);
    setHistoryIndex(newHistory.length - 1);
  };

  const undo = () => {
    if (historyIndex > 0) {
      setHistoryIndex(historyIndex - 1);
      setElements(history[historyIndex - 1]);
    } else {
      setElements([]);
      setHistoryIndex(-1);
    }
  };

  const clear = () => {
    setElements([]);
    setCurrentElement(null);
    saveHistory([]);
  };

  const downloadImage = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const link = document.createElement('a');
    link.download = `${eye}-${type}-diagram.png`;
    link.href = canvas.toDataURL('image/png');
    link.click();
  };

  return (
    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
      <div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-b">
        <div className="flex items-center gap-2">
          <span className="px-2 py-1 bg-teal-100 text-teal-700 rounded font-medium text-sm">{eye}</span>
          <span className="text-sm text-gray-600 capitalize">{type} Segment</span>
        </div>
        
        {!readOnly && (
          <div className="flex items-center gap-1">
            <button
              onClick={undo}
              className="p-2 rounded hover:bg-gray-200 text-gray-600"
              title="Undo"
            >
              <RotateCcw className="h-4 w-4" />
            </button>
            <button
              onClick={clear}
              className="p-2 rounded hover:bg-gray-200 text-gray-600"
              title="Clear"
            >
              <Eraser className="h-4 w-4" />
            </button>
            <button
              onClick={downloadImage}
              className="p-2 rounded hover:bg-gray-200 text-gray-600"
              title="Download"
            >
              <Download className="h-4 w-4" />
            </button>
          </div>
        )}
      </div>
      
      {!readOnly && (
        <div className="flex items-center gap-2 px-4 py-2 bg-gray-50 border-b">
          {/* Tools */}
          <div className="flex items-center gap-1 border-r pr-3">
            <button
              onClick={() => setTool('pencil')}
              className={`p-2 rounded ${tool === 'pencil' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Pencil"
            >
              <Pencil className="h-4 w-4" />
            </button>
            <button
              onClick={() => setTool('line')}
              className={`p-2 rounded ${tool === 'line' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Line"
            >
              <Minus className="h-4 w-4" />
            </button>
            <button
              onClick={() => setTool('circle')}
              className={`p-2 rounded ${tool === 'circle' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Circle"
            >
              <Circle className="h-4 w-4" />
            </button>
            <button
              onClick={() => setTool('rectangle')}
              className={`p-2 rounded ${tool === 'rectangle' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Rectangle"
            >
              <Square className="h-4 w-4" />
            </button>
            <button
              onClick={() => setTool('text')}
              className={`p-2 rounded ${tool === 'text' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Text"
            >
              <Type className="h-4 w-4" />
            </button>
            <button
              onClick={() => setTool('eraser')}
              className={`p-2 rounded ${tool === 'eraser' ? 'bg-teal-100 text-teal-600' : 'hover:bg-gray-200 text-gray-600'}`}
              title="Eraser"
            >
              <Eraser className="h-4 w-4" />
            </button>
          </div>
          
          {/* Colors */}
          <div className="flex items-center gap-1 border-r pr-3">
            {COLORS.map(c => (
              <button
                key={c}
                onClick={() => setColor(c)}
                className={`w-5 h-5 rounded-full border-2 ${color === c ? 'border-gray-800' : 'border-transparent'}`}
                style={{ backgroundColor: c }}
              />
            ))}
          </div>
          
          {/* Stroke Width */}
          <div className="flex items-center gap-1">
            {STROKE_WIDTHS.map(w => (
              <button
                key={w}
                onClick={() => setStrokeWidth(w)}
                className={`w-6 h-6 rounded flex items-center justify-center ${
                  strokeWidth === w ? 'bg-teal-100' : 'hover:bg-gray-200'
                }`}
              >
                <div 
                  className="rounded-full bg-gray-800"
                  style={{ width: w * 2, height: w * 2 }}
                />
              </button>
            ))}
          </div>
        </div>
      )}
      
      <div className="relative">
        <canvas
          ref={canvasRef}
          width={300}
          height={300}
          className="w-full aspect-square cursor-crosshair"
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
        />
      </div>
    </div>
  );
}
