"use client";

import Draggable from "@/components/Draggable";
import Droppable from "@/components/Droppable";
import {
  getQuestionForSingleAnswer,
  makeWordSplitBySign,
} from "@/utils/fib/fibLogic";
import { Answer } from "@/zustand/useFib";
import {
  DndContext,
  KeyboardSensor,
  MouseSensor,
  TouchSensor,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import { useState } from "react";

export interface FIBMulti {
  questionWithOption: string;
  correctAnswers: string[];
  time: {
    waitingTime: number;
    questionSolvingTime: number;
  };
}

export default function FibSingle({
  currentQuestion,
  answer,
}: {
  currentQuestion: string;
  answer: string;
}) {
  const [counter, setCounter] = useState(0);
  const submittedAnswers: string[] = [];
  const [mark, setMark] = useState(0);
  const [isScoreButtonVisible, setIsScoreButtonVisible] = useState(true);
  const [showAnswer, setShowAnswer] = useState(true);

  const correctAnswers = answer.split(",");

  const textWithMultipleOptions = currentQuestion;
  const wordlist = makeWordSplitBySign(textWithMultipleOptions);
  const question = getQuestionForSingleAnswer(wordlist);
  // const options = getMultipleAnswers(wordlist);

  function checkAnswer() {
    setMark(0);
    correctAnswers.map((correctAnswer, index) => {
      if (correctAnswer && submittedAnswers.at(index)) {
        if (correctAnswer === submittedAnswers.at(index)) {
          setMark((old) => old + 1);
        }
      }
    });
    setIsScoreButtonVisible(false);
  }

  function handleAnswerChange(index: number, answer: string) {
    const ans: Answer = { position: index, answer };
    submittedAnswers[index - 1] = answer;
  }

  const mouseSensor = useSensor(MouseSensor);
  const touchSensor = useSensor(TouchSensor);
  const keyboardSensor = useSensor(KeyboardSensor);

  const [output, setOutput] = useState<string[]>();

  const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);

  const testQuestion = question.length - 1;
  const myArray = Array(testQuestion).map((item, index) => item);

  // State to track the list of draggable items
  const [draggables, setDraggables] = useState(
    correctAnswers.map((text, index) => ({ id: index, text }))
  );

  const [droppableTexts, setDroppableTexts] = useState<{
    [key: number]: string;
  }>({});

  function handleDragEnd(event: { active: any; over: any }) {
    const { active, over } = event;
    if (active.data.current.text && over) {
      const activeText = active.data.current.text;
      const overId = over.id;

      // Update the text for the Droppable
      setDroppableTexts((old) => ({
        ...old,
        [overId]: activeText,
      }));

      // Remove the draggable item
      setDraggables((old) => old.filter((item) => item.text !== activeText));
    }
  }

  return (
    <div className="px-4">
      <p>testQuestion: {JSON.stringify(myArray)}</p>
      <div className="text-slate-600 leading-7">
        <DndContext onDragEnd={handleDragEnd} sensors={sensors}>
          {question.map((item: string, questionIndex: number) => {
            if (item.includes("#")) {
              return (
                <span key={questionIndex}>
                  <Droppable
                    id={questionIndex}
                    text={droppableTexts[questionIndex] || ""}
                    key={questionIndex}
                  />

                  <span>{item.slice(1)}</span>
                </span>
              );
            } else {
              return <span key={questionIndex}>{item}</span>;
            }
          })}

          <div className="my-5 flex gap-5">
            {draggables.map((item, index) => (
              <Draggable button_name={item.text} id={item.id} key={item.id} />
            ))}
          </div>
        </DndContext>
      </div>

      <div className="flex gap-5 my-8">
        <button
          onClick={checkAnswer}
          className="btn btn-sm w-fit"
          disabled={!isScoreButtonVisible}
        >
          Submit
        </button>

        <button
          onClick={() => {
            setShowAnswer((old) => !old);
          }}
          className="btn btn-sm w-fit"
          disabled={!showAnswer}
        >
          Show answer
        </button>
      </div>

      {isScoreButtonVisible ? null : (
        <div className="p-2 my-10 w-fit">
          <p className="text-white bg-slate-600 p-2"> Marks: {mark}</p>
        </div>
      )}

      {showAnswer ? null : (
        <div className="p-2 my-10 w-fit">
          <p>Correct answer: {answer}</p>
        </div>
      )}
    </div>
  );
}
""" the first draggable item is not draggable"""