/**
 * Canvas 기반 이미지 그리기 컴포넌트
 *
 * 절곡품 전개도 등 이미지를 직접 그리거나 편집
 */

'use client';

import { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Pen,
  Square,
  Circle,
  Type,
  Minus,
  Eraser,
  Trash2,
  Undo2,
  Save,
} from 'lucide-react';

interface DrawingCanvasProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave?: (imageData: string) => void;
  initialImage?: string;
  title?: string;
  description?: string;
}

type Tool = 'pen' | 'line' | 'rect' | 'circle' | 'text' | 'eraser';

export function DrawingCanvas({
  open,
  onOpenChange,
  onSave,
  initialImage,
  title = '이미지 편집기',
  description = '품목 이미지를 그리거나 편집합니다.',
}: DrawingCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [tool, setTool] = useState<Tool>('pen');
  const [color, setColor] = useState('#000000');
  const [lineWidth, setLineWidth] = useState(2);
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
  const [history, setHistory] = useState<ImageData[]>([]);
  const [historyStep, setHistoryStep] = useState(-1);

  const colors = [
    '#000000',
    '#FF0000',
    '#00FF00',
    '#0000FF',
    '#FFFF00',
    '#FF00FF',
    '#00FFFF',
    '#FFA500',
    '#800080',
    '#FFC0CB',
  ];

  useEffect(() => {
    if (open && canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      if (ctx) {
        // 캔버스 초기화
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 초기 이미지가 있으면 로드
        if (initialImage) {
          const img = new Image();
          img.onload = () => {
            ctx.drawImage(img, 0, 0);
            saveToHistory();
          };
          img.src = initialImage;
        } else {
          saveToHistory();
        }
      }
    }
  }, [open, initialImage]);

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

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

    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const newHistory = history.slice(0, historyStep + 1);
    newHistory.push(imageData);
    setHistory(newHistory);
    setHistoryStep(newHistory.length - 1);
  };

  const undo = () => {
    if (historyStep > 0) {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      const newStep = historyStep - 1;
      ctx.putImageData(history[newStep], 0, 0);
      setHistoryStep(newStep);
    }
  };

  const clearCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    saveToHistory();
  };

  const getMousePos = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (!canvas) return { x: 0, y: 0 };
    const rect = canvas.getBoundingClientRect();
    // 실제 캔버스 크기와 표시 크기의 비율 계산
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    return {
      x: (e.clientX - rect.left) * scaleX,
      y: (e.clientY - rect.top) * scaleY,
    };
  };

  const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const pos = getMousePos(e);
    setStartPos(pos);
    setIsDrawing(true);

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

    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    if (tool === 'pen' || tool === 'eraser') {
      ctx.beginPath();
      ctx.moveTo(pos.x, pos.y);
      if (tool === 'eraser') {
        ctx.globalCompositeOperation = 'destination-out';
      } else {
        ctx.globalCompositeOperation = 'source-over';
      }
    }
  };

  const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDrawing) return;

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

    const pos = getMousePos(e);

    if (tool === 'pen' || tool === 'eraser') {
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke();
    } else {
      // 도형 그리기: 임시로 표시하기 위해 이전 상태 복원
      if (historyStep >= 0) {
        ctx.putImageData(history[historyStep], 0, 0);
      }

      ctx.globalCompositeOperation = 'source-over';
      ctx.strokeStyle = color;
      ctx.fillStyle = color;

      if (tool === 'line') {
        ctx.beginPath();
        ctx.moveTo(startPos.x, startPos.y);
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
      } else if (tool === 'rect') {
        const width = pos.x - startPos.x;
        const height = pos.y - startPos.y;
        ctx.strokeRect(startPos.x, startPos.y, width, height);
      } else if (tool === 'circle') {
        const radius = Math.sqrt(
          Math.pow(pos.x - startPos.x, 2) + Math.pow(pos.y - startPos.y, 2)
        );
        ctx.beginPath();
        ctx.arc(startPos.x, startPos.y, radius, 0, 2 * Math.PI);
        ctx.stroke();
      }
    }
  };

  const stopDrawing = () => {
    if (isDrawing) {
      setIsDrawing(false);
      saveToHistory();
    }
  };

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

    const imageData = canvas.toDataURL('image/png');
    onSave?.(imageData);
    onOpenChange(false);
  };

  const handleText = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const text = prompt('입력할 텍스트:');
    if (text) {
      ctx.font = `${lineWidth * 8}px sans-serif`;
      ctx.fillStyle = color;
      ctx.fillText(text, 50, 50);
      saveToHistory();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 도구 모음 */}
          <div className="space-y-3 p-3 border rounded-lg bg-muted/30">
            {/* 첫 번째 줄: 그리기 도구 */}
            <div className="flex items-center gap-2 flex-wrap">
              <Button
                variant={tool === 'pen' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTool('pen')}
                type="button"
              >
                <Pen className="h-4 w-4" />
              </Button>
              <Button
                variant={tool === 'line' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTool('line')}
                type="button"
              >
                <Minus className="h-4 w-4" />
              </Button>
              <Button
                variant={tool === 'rect' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTool('rect')}
                type="button"
              >
                <Square className="h-4 w-4" />
              </Button>
              <Button
                variant={tool === 'circle' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTool('circle')}
                type="button"
              >
                <Circle className="h-4 w-4" />
              </Button>
              <Button
                variant={tool === 'text' ? 'default' : 'outline'}
                size="sm"
                onClick={() => {
                  setTool('text');
                  handleText();
                }}
                type="button"
              >
                <Type className="h-4 w-4" />
              </Button>
              <Button
                variant={tool === 'eraser' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTool('eraser')}
                type="button"
              >
                <Eraser className="h-4 w-4" />
              </Button>

              <div className="h-6 w-px bg-border mx-1" />

              <Button
                variant="outline"
                size="sm"
                onClick={undo}
                disabled={historyStep <= 0}
                type="button"
              >
                <Undo2 className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={clearCanvas}
                type="button"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>

            {/* 두 번째 줄: 색상 팔레트 */}
            <div className="flex items-center gap-2 flex-wrap">
              <Label className="text-sm whitespace-nowrap">색상:</Label>
              <div className="flex gap-1 flex-wrap">
                {colors.map((c) => (
                  <button
                    key={c}
                    type="button"
                    className={`w-6 h-6 rounded border-2 ${
                      color === c ? 'border-primary' : 'border-transparent'
                    }`}
                    style={{ backgroundColor: c }}
                    onClick={() => setColor(c)}
                  />
                ))}
              </div>
            </div>

            {/* 세 번째 줄: 선 두께 조절 */}
            <div className="flex items-center gap-4">
              <Label className="text-sm whitespace-nowrap">
                선 두께: {lineWidth}px
              </Label>
              <Slider
                value={[lineWidth]}
                onValueChange={(value) => setLineWidth(value[0])}
                min={1}
                max={20}
                step={1}
                className="flex-1"
              />
            </div>
          </div>

          {/* 캔버스 */}
          <div className="border rounded-lg overflow-hidden bg-white w-full">
            <canvas
              ref={canvasRef}
              width={600}
              height={400}
              className="cursor-crosshair w-full block"
              onMouseDown={startDrawing}
              onMouseMove={draw}
              onMouseUp={stopDrawing}
              onMouseLeave={stopDrawing}
            />
          </div>

          {/* 하단 버튼 */}
          <div className="flex justify-end gap-2">
            <Button
              variant="outline"
              onClick={() => onOpenChange(false)}
              type="button"
            >
              취소
            </Button>
            <Button
              className="bg-blue-600 hover:bg-blue-700"
              onClick={handleSave}
              type="button"
            >
              <Save className="h-4 w-4 mr-2" />
              저장
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}