import React, { useRef, useState, DragEvent } from "react";
import { CreateQuestionData } from "../types";
import { Question } from "./Question";
import { DraggableItem } from "./DraggableItem";

type Props = {
  questions: CreateQuestionData[];
  handleQuestion: Function;
  deleteQuestion: Function;
};

export const QuestionsList = ({
  questions,
  handleQuestion,
  deleteQuestion,
}: Props) => {
  const [items, setItems] = useState(questions);
  const currentItem = useRef<HTMLDivElement>();
  const [currentItemId, setCurrentItemId] = useState<string>("");

  function arrayMove(questionArr: any[], oldIndex: number, newIndex: number) {
    questionArr.splice(newIndex, 0, questionArr.splice(oldIndex, 1)[0]);
    return questionArr; // for testing
  }

  const onDragStart = (e: DragEvent<HTMLDivElement>) => {
    currentItem.current = e.currentTarget;
    const { id } = e.currentTarget;
    const index = items.findIndex(
      (question: CreateQuestionData) => question._id === String(id)
    );
    console.log(id, "drag start, ", "start index: ", index);
    setCurrentItemId(id);
  };

  const onDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    // const { id } = e.target;
    const { id } = e.currentTarget;
    const curId = e.currentTarget.id;
    const currentItemIndex = items.findIndex(
      (question: CreateQuestionData) => question._id === curId
    );
    const dropIndex = items.findIndex(
      (question: CreateQuestionData) => question.id === String(id)
    );
    console.log(
      id,
      "drop, ",
      "current question:",
      curId,
      ", drop index:",
      dropIndex,
      ", currentItem index:",
      currentItemIndex
    );

    const newArray = arrayMove(questions, currentItemIndex, dropIndex);
    newArray.forEach((question, index) => {
      question.order = index;
    });
    console.log("new array=", newArray);
    setItems([...newArray]);
  };

  return (
    <>
      {questions.map((question) => (
        <DraggableItem
          key={question._id}
          currentItemId={currentItemId}
          question={question}
          onDragStart={onDragStart}
          onDrop={onDrop}
        >
          <Question
            key={question._id}
            element={question}
            handleQuestion={handleQuestion}
            deleteQuestion={deleteQuestion}
          />
        </DraggableItem>
      ))}
    </>
  );
};
