import { KonvaEventObject } from 'konva/lib/Node';
import React, { FC, useEffect, useRef, useState } from 'react';
import { Circle, Group, Image, Layer, Stage } from 'react-konva';
import { Html } from 'react-konva-utils';
import useImage from 'use-image';
import commentIcon from '../../assets/comment.svg';
import { Comment } from '../../types/job';

type PlanProps = {
  isAddingComment: boolean;
  comments: Comment[];
  onAddComment: (comment: Comment) => void;
  onEditComment: (comment: Comment) => void;
  currentPage: number;
  plan: string;
};

export const Plan: FC<PlanProps> = ({
  isAddingComment,
  comments,
  onAddComment,
  onEditComment,
  currentPage,
  plan,
}) => {
  const ref = useRef<HTMLDivElement>(null);
  const [carImage] = useImage(commentIcon);
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const updateDimensions = () => {
      if (ref.current) {
        setDimensions({
          width: ref.current.clientWidth,
          height: ref.current.clientHeight,
        });
      }
    };

    updateDimensions();
    window.addEventListener('resize', updateDimensions);
    return () => window.removeEventListener('resize', updateDimensions);
  }, []);

  const handleStageClick = (e: KonvaEventObject<MouseEvent>) => {
    if (!isAddingComment) return;

    const stage = e.target.getStage();
    const pos = stage?.getPointerPosition();

    const newComment: Comment = {
      id: Date.now().toString(),
      content: '',
      position: { x: pos?.x ?? 0, y: pos?.y ?? 0 },
      user: 'U',
      time: new Date(),
      page: currentPage,
    };
    onAddComment(newComment);
  };

  const handleTextChange = (
    e: React.ChangeEvent<HTMLTextAreaElement>,
    comment: Comment,
  ) => {
    const newComments = comments.find((c) => c.id === comment.id);
    if (newComments) {
      newComments.content = e.target.value;
      onEditComment(newComments);
    }
  };

  const handleDragEnd = (e: KonvaEventObject<DragEvent>, comment: Comment) => {
    const newComments = comments.find((c) => c.id === comment.id);
    if (newComments) {
      const position = e.target.getPosition();
      if (position) {
        newComments.position = {
          x: position.x,
          y: position.y,
        };
        onEditComment(newComments);
      }
    }
  };

  return (
    <div className="h-full w-full flex flex-1 justify-center overflow-hidden">
      <div ref={ref} className="relative h-full w-full">
        <img src={plan} className="absolute h-full" />
        <Stage
          width={dimensions.width}
          height={dimensions.height}
          style={{ position: 'absolute' }}
          onClick={handleStageClick}
        >
          <Layer>
            {carImage &&
              comments
                .filter((c) => c.page === currentPage)
                .map((comment, i) => (
                  <Group
                    key={i}
                    draggable
                    onDragEnd={(e) => handleDragEnd(e, comment)}
                    x={comment.position.x}
                    y={comment.position.y}
                  >
                    <Circle radius={20} fill="white" stroke="#ddd" />
                    <Image
                      image={carImage}
                      x={-15}
                      y={-15}
                      width={30}
                      height={30}
                    />
                    <Group x={+20} y={-20}>
                      <Html>
                        <textarea
                          className="border border-gray-300 bg-white p-0.5"
                          value={comment.content}
                          onChange={(e) => handleTextChange(e, comment)}
                          placeholder="input"
                          rows={2}
                        />
                      </Html>
                    </Group>
                  </Group>
                ))}
          </Layer>
        </Stage>
      </div>
    </div>
  );
};
