import { style } from "d3";
import React, { DragEvent } from "react";
import { CreateQuestionData } from "../types";

type Props = {
  children: any;
  currentItemId: string;
  question: CreateQuestionData;
  onDragStart: Function;
  onDrop: Function;
};

export const DraggableItem = ({
  children,
  currentItemId,
  question,
  onDragStart,
  onDrop,
}: Props) => {
  console.log("current item id:", currentItemId);
  let counter = 0;

  const handleDragStart = (e: DragEvent<HTMLDivElement>) => {
    const { id } = e.currentTarget;
    console.log(id, "drag start");
    onDragStart(e);
  };

  const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
    const { id } = e.currentTarget;
    console.log(id, "drag enter");
    counter++;
    console.log("counter:", counter);
    if (currentItemId !== String(id)) {
      e.currentTarget.classList.add("active");
    }
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    const { id } = e.currentTarget;
    console.log(id, "drag leave");
    counter--;
    console.log("counter:", counter);
    if (counter == 0) {
      console.log("counter in handle drag leave", counter);
      e.currentTarget.classList.remove("active");
    }
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const { id } = e.currentTarget;
    console.log(id, "drag over");
  };

  const handleDragEnd = (e: DragEvent<HTMLDivElement>) => {
    const { id } = e.currentTarget;
    console.log(id, "drag end");
    e.currentTarget.classList.remove("active");
    e.currentTarget.classList.remove("hint");
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const { id } = e.currentTarget;
    console.log(id, "drop");
    onDrop(e);
    e.currentTarget.classList.remove("active");
    e.currentTarget.classList.remove("hint");
  };

  return (
    <div
      id={question._id}
      draggable={true}
      className="flex flex-col container w-4/5 h-auto border-2 items-center m-3 rounded-lg p-0 cursor-move"
      onDragStart={handleDragStart}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {children}
    </div>
  );
};
