const { useEffect, useMemo, useState } = React;

const normalizeText = (value) =>
  value
    .toLowerCase()
    .replace(/[.?!।]/g, "")
    .replace(/\s+/g, " ")
    .trim();

const splitWords = (value) => normalizeText(value).split(" ").filter(Boolean);

const SentenceBuilder = ({ question, onAnswer }) => {
  const shuffled = useMemo(() => window.shuffle(question.words), [question.id]);
  const correctWords = useMemo(() => splitWords(question.sentence), [question.id]);
  const [bank, setBank] = useState(shuffled);
  const [answer, setAnswer] = useState([]);
  const [attempts, setAttempts] = useState(0);
  const [locked, setLocked] = useState(false);
  const [showSolution, setShowSolution] = useState(false);

  useEffect(() => {
    setBank(shuffled);
    setAnswer([]);
    setAttempts(0);
    setLocked(false);
    setShowSolution(false);
  }, [question.id, shuffled]);

  const handleAdd = (word, indexToRemove) => {
    if (locked) return;
    setBank((prev) => prev.filter((_, index) => index !== indexToRemove));
    setAnswer((prev) => [...prev, word]);
  };

  const handleRemove = (indexToRemove) => {
    if (locked) return;
    setAnswer((prev) => prev.filter((_, index) => index !== indexToRemove));
    setBank((prev) => [...prev, answer[indexToRemove]]);
  };

  const checkAnswer = () => {
    if (locked) return;
    const normalizedAnswer = answer.map((word) => normalizeText(word));
    const correct =
      normalizedAnswer.length === correctWords.length &&
      normalizedAnswer.every((word, index) => word === correctWords[index]);

    if (correct) {
      setLocked(true);
      onAnswer(true);
      return;
    }

    const nextAttempts = attempts + 1;
    setAttempts(nextAttempts);
    if (nextAttempts >= 2) {
      setLocked(true);
      setShowSolution(true);
      onAnswer(false);
    }
  };

  const handleReset = () => {
    if (locked) return;
    setBank(shuffled);
    setAnswer([]);
  };

  const answerFeedback = answer.map((word, index) => {
    const normalizedWord = normalizeText(word);
    const expected = correctWords[index];
    if (!expected) return "wrong";
    return normalizedWord === expected ? "correct" : "wrong";
  });

  return (
    <div>
      <h3>Arrange the sentence</h3>
      <p className="sentence-meaning">{question.meaning}</p>
      {question.nepali ? (
        <p className="sentence-nepali">{question.nepali}</p>
      ) : null}
      {question.translationHint ? (
        <p className="sentence-hint">Hint: {question.translationHint}</p>
      ) : null}

      <div className="sentence-answer">
        {answer.length === 0 ? (
          <div className="sentence-placeholder">Tap words to build the sentence</div>
        ) : (
          answer.map((word, index) => (
            <button
              key={`${word}-${index}`}
              className={`word-chip ${locked ? answerFeedback[index] : ""}`}
              onClick={() => handleRemove(index)}
              disabled={locked}
            >
              {word}
            </button>
          ))
        )}
      </div>

      <div className="sentence-bank">
        {bank.map((word, index) => (
          <button
            key={`${word}-${index}`}
            className="word-chip"
            onClick={() => handleAdd(word, index)}
            disabled={locked}
          >
            {word}
          </button>
        ))}
      </div>

      <div className="footer-actions">
        <button className="btn-secondary btn" onClick={handleReset} disabled={locked}>
          Reset
        </button>
        <button className="btn" onClick={checkAnswer} disabled={answer.length === 0 || locked}>
          Submit
        </button>
      </div>

      {showSolution ? (
        <div className="solution">
          Correct answer: <strong>{question.sentence}</strong>
        </div>
      ) : null}
    </div>
  );
};
